为什么不使用is_const类型特征将const引用视为const? [英] Why isn't a const reference considered const using the is_const type trait?
问题描述
我对以下代码感到惊讶:
I was rather surprised that the following code:
#include <iostream>
#include <type_traits>
using namespace std;
int main(int argc, char* argv[]) {
cout << boolalpha << is_const<const float&>::value << endl;
return 0;
}
打印 false
。删除引用可以正常工作:
Prints false
. Removing the reference works correctly:
#include <iostream>
#include <type_traits>
using namespace std;
int main(int argc, char* argv[]) {
cout << boolalpha << is_const<remove_reference<const float&>::type>::value << endl;
return 0;
}
打印出 true
。
两者都是使用G ++版本的 g ++ -std = c ++ 11 test.cpp
编译的: / p>
Both were compiled with g++ -std=c++11 test.cpp
, using G++ version:
g++ (Ubuntu 5.3.0-1ubuntu1~14.04) 5.3.0 20151204
考虑一下,我可以理解这里有两种类型:引用类型和被引用的类型。引用的类型为 const
,因此第二种情况很有意义。对于第一种情况,如果引用的类型为 const
或始终为 true
,我希望它返回,因为引用AFAIK不能重新分配。
Thinking about it, I can understand that there are two types in play here: the reference type and the type that is referenced. The type that is referenced is const
, so the second case makes sense. For the first case, I would expect it to either return if the referenced type is const
or always true
instead, because references AFAIK can't be "reassigned".
为什么它返回 false
?
推荐答案
结果正确。
引用绝不是 const
,因为它们不能通过 cv认证。您的说法是正确的,因为它们无法重新分配(因此在某种意义上是不变的),但这与 const
限定的含义不同。
References are never const
, because they cannot be cv-qualified. You are correct in saying that they cannot be reassigned (and are, as such, immutable in a sense), but that is not the same as being const
-qualified.
如果纯粹由于所指对象为 const <而得到
true
/ code>,那么在所有其他情况下,这将与 is_const
的含义完全不一致。例如考虑指针。 is_const< int const *> :: value
应该是什么?
If you got true
purely because the referent is const
, then that would be completely inconsistent with the meaning of is_const
in all other cases. Consider, for example, pointers. What should is_const<int const*>::value
be?
这篇关于为什么不使用is_const类型特征将const引用视为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!