c++ - 在 Bjarne 的这个示例中,为什么可以将 const 限定对象传递给非 const 参数?

标签 c++ c++11

我正在阅读 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/

相关文章:

c++ - 将唯一指针指向共享指针是否可以?

c++ - 在源代码中使用 C++ 库的 CMakeLists

C++11 operator""with double parameter

c++ - 为什么 shared_ptr<T> 期望在 T 中复制/移动构造函数?

c++ - std::vector 适用于不可默认构造的类?

c++ - 使用 std::enable_if 保护复制构造函数

c++ - 为什么 C++ STL 使用 RBtree 来实现 "std::map"?

c++ - 为什么在类中定义的 C++ 成员函数不会产生重复符号,而在 C 中会产生重复符号?

python - 无法在场景中正确定位 QGraphicsRectItem

c++ - 如何将 SHA1 转换为无符号长整型数组 [5]?