【问题标题】:make 'const' work with the result of type traits使 'const' 与类型特征的结果一起工作
【发布时间】:2014-03-16 10:26:07
【问题描述】:
int main(int argc, char* argv[]) {
  const int i = 10;
  using Type = typename std::conditional<false, int, int&>::type;
  const Type r = i; // It seems this 'const' does not have any effect.
  std::cout << r << std::endl;
}

上面的代码在gcc4.8.1 -std=c++11上无法编译,错误信息如下:“invalid initialization of type of type {aka int&}' from expression of 'const int' . 但是,如果我像这样更改代码,它将起作用:

int main(int argc, char* argv[]) {
  const int i = 10;
  using Type = typename std::conditional<false, const int, const int&>::type;
  Type r = i;
  std::cout << r << std::endl;
}

有没有人可以告诉我原因?

【问题讨论】:

    标签: c++ c++11 std typetraits


    【解决方案1】:

    在第一个示例中,const 无效,因为它绑定到错误的类型:在引用之后而不是之前。请参阅https://www.securecoding.cert.org/confluence/display/cplusplus/DCL33-CPP.+Never+qualify+a+variable+of+reference+type+with+const+or+volatile 了解一些可能有所帮助的详细信息,但基本上:

    const int& // reference to immutable int
    int const& // reference to immutable int
    int& const // immutable reference to int
    

    当然,所有的引用都是不可变的(不能重新安装),所以你拥有的最后一个引用有点没用。发生这种情况是因为您在引用已应用于类型之后应用 const,这为您提供了我编写的第三个示例,而不是第一个或第二个示例。

    【讨论】:

    • (尽管这样输入int&amp; const 是无效的。这种事情只有在const 应用于恰好是引用类型的typedef 或模板参数时才允许。)
    【解决方案2】:

    你也可以改变

      const int i = 10;
    

      int i = 10;
    

    让它工作。

    当你说

    using Type = typename std::conditional<false, int, int&>::type;
    

    相当于:

    typedef int& Type;
    

    当你说

    const Type r = i;
    

    你说的是

    int& const r = i;
    

    这不是一回事

    const int& r = i;
    

    John Zwinck 在他的回答中解释了它们之间的区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 2012-01-14
      • 2017-10-28
      • 2018-07-12
      相关资源
      最近更新 更多