我正在阅读 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()
如何接受常量引用。 Bjarne 只是声明 const 将被推导到模板参数中。这到底是什么意思?
最佳答案
如果你传入一个const X
类型的左值,那么A1
会被推导为const X
,你会得到一个函数看起来像
std::shared_ptr<T> factory(const X& a1) { ... }
关于c++ - 在 Bjarne 的这个示例中,为什么可以将 const 限定对象传递给非 const 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24645013/