c++ - 'const' 是否取消了通用引用的资格?

标签 c++ c++11 templates

我有一个使用通用引用的 ctor 的人类类

class Human {
 public:
  template<typename T>
  explicit Human(T&& rhs) {
    // do some initialization work
  }

  Human(const Human& rhs);  // the default ctor I don't care about
}

现在如果我有一个 const Human 对象

const Human one_I_do_not_care; // then play with that
Human the_human_I_care(one_I_do_not_care)  // now create another one

最后一行是使用模板构造函数还是默认构造函数?我的理解是“const”会取消模板 ctor 的资格,对吗?

Human the_human_I_care(one_I_do_not_care)  // line in question

通过 const 取消模板 ctor 的资格,我的意思是添加 const 然后它不会匹配模板 ctor,不是它仍然匹配两个但编译器选择一个。

最佳答案

Does the last line use the template ctor or the default ctor? My understanding is the const will disqualify the template ctor, am I correct?

没有。您正在传递一个 const-qualified Human 作为参数。由于两个构造函数将同样匹配(即:如果模板将被实例化为采用const Human&),那么非模板构造函数优先于模板(并且不会发生 const Human& 参数的模板实例化)。

关于c++ - 'const' 是否取消了通用引用的资格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48359328/

相关文章:

c++ - 当调用具有等待条件变量的线程对象的析构函数时会发生什么?

c++ - 标准库容器的通用函数模板

c++ - 多态失败

c++ - 如何在 C++ 中创建多线程应用程序

c++ - 我如何在 C++ 的子目录中创建文件?

c++ - 在libc++和libstdc++之间的std::map上使用std::find时的实现差异

c++ - 如何从函数返回 std::seed_seq 对象

c++ - C++ 编译器是否优化按值返回成员变量

c++ - 我在这一行代码中的语法有什么问题(指针和引用以及取消引用哦,我的)?

c++ - 如何通过可变构造函数调用复制构造函数?