我有一个使用通用引用的 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/