代码之家  ›  专栏  ›  技术社区  ›  WhatABeautifulWorld

“const”是否取消了通用引用的资格?

  •  6
  • WhatABeautifulWorld  · 技术社区  · 8 年前

    我有一个使用通用引用的带有ctor的human类

    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 one_I_do_not_care; // then play with that
    Human the_human_I_care(one_I_do_not_care)  // now create another one
    

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

    Human the_human_I_care(one_I_do_not_care)  // line in question
    

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

    1 回复  |  直到 8 年前
        1
  •  8
  •   jfMR    8 年前

    最后一行是使用模板ctor还是默认ctor?我的理解是 const 将取消模板ctor的资格,对吗?

    不,你正在通过 常量 -合格的 Human 作为论据。因为两个施工人员都会 平分秋色 (即:如果模板将被实例化为 const Human& ),然后 非模板 构造函数优先于模板(对于 施工人员和; 参数)。