【问题标题】:Why does std::is_const<const int&>::value evaluate to false?为什么 std::is_const<const int&>::value 评估为假?
【发布时间】:2014-06-04 05:31:20
【问题描述】:

这是问题How to check if object is const or not?的衍生。

看到下面这个程序我很惊讶

#include <iostream>
#include <type_traits>

int main() 
{
   std::cout << std::boolalpha;
   std::cout << std::is_const<const int&>::value << "\n";
}

产生了这个输出

错误的

在什么情况下将const int&amp; 视为非常量类型有意义?

【问题讨论】:

  • is_const&lt;T&gt; 被定义为“T 是 const-qualified”。引用不能是 cv 限定的,因此从语言的角度来看是有意义的。
  • @Mat,您介意将您的评论转换为答案吗?这似乎包含了最好的答案。

标签: c++ c++11 typetraits


【解决方案1】:

也许用这个例子会更容易理解

std::cout << std::is_const<int const *>::value << "\n";  // pointer to const int
std::cout << std::is_const<int * const>::value << "\n";  // const pointer to int

输出:

false
true

第一种类型是指向const int 的指针,而第二种int * 本身就是const。因此它产生true,而前者是false。同样,您对const int 的引用。如果int&amp; const 有效,则结果为true

【讨论】:

  • 由于引用类型的变量在初始化后不能引用另一个对象,因此std::is_const&lt;int&amp;&gt;::valuestd::is_const&lt;const int&amp;&gt;::value 评估为'true' 比false 更有意义.
  • @RSahu 我不明白你为什么这么想。我相信你明白,int const&amp; 中的const 表示int 不能被修改。 is_const 的目的是表明 T 是否为 const-qualified(引自 20.10.4.3)。在这两种情况下,您都列出了T = int&amp;;显然T 不是const。在任何一种情况下返回 true 都是违反直觉的。
  • 我明白这一点。也许我发现很难证明它的特定行为是正确的。将引用变量的 const-ness 与其引用的类型的 const-ness 相同,对我来说更有意义。
  • @RSahu 我可以看到你来自哪里,但你会同意那种 const 因为另一个选项是不正确的 行为只适用于引用类型。对于T = U* 的情况,它甚至没有意义。这将是另一个每个人都需要记住的特殊情况。
  • 是的。我同意。它仅适用于引用类型。请理解我是从语言用户的角度发言。从语言开发人员的角度来看,is_const 的行为可能更有意义。
【解决方案2】:

引用上的const 限定符仅表示该值不能通过引用修改。它仍然可以通过其他方式进行修改。例如:

int a = 1;
const int &b = a;

std::cout << b << std::endl;  // Prints 1

a = 2;

std::cout << b << std::endl;  // Prints 2

因此,您不能假设 const 引用的值实际上是恒定的。

【讨论】:

  • 不知道为什么这会引起反对。它正确地指出这里的const 仅适用于涉及b 的表达式类型。 ab 本身都不是 const。 (也就是说,Praetorian 的答案要清楚得多)
  • 这是真的,但与问题无关
猜你喜欢
  • 1970-01-01
  • 2019-01-03
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多