加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在Bjarne的这个例子中,为什么你可以将const限定对象传递给

发布时间:2020-12-16 09:53:15 所属栏目:百科 来源:网络整理
导读:我正在阅读Bjarne的 Rvalue Reference Quick Look并进入下面的例子: template class T,class A1std::shared_ptrTfactory(A1 a1){ return std::shared_ptrT(new T(a1));} This is much better. If a const-qualified type is passed to the factory,the cons
我正在阅读Bjarne的 Rvalue Reference Quick Look并进入下面的例子:

template <class T,class A1>
std::shared_ptr<T>
factory(A1& a1)
{
    return std::shared_ptr<T>(new T(a1));
}

This is much better. If a const-qualified type is passed to the
factory,the const will be deduced into the template parameter (A1 for
example) and then properly forwarded to T’s constructor.

我不明白:: factory()如何接受const引用. Bjarne只是声明const将被推导到模板参数中.这到底是什么意思?

解决方法

如果你传入一个const X类型的左值,那么A1将被推导为const X,你会得到一个看起来像的函数

std::shared_ptr<T> factory(const X& a1) { ... }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读