【问题标题】:Why isn't a const reference considered const using the is_const type trait? [duplicate]为什么不使用 is_const 类型特征将 const 引用视为 const ? [复制]
【发布时间】:2015-12-05 15:11:14
【问题描述】:

我很惊讶下面的代码:

#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。删除引用可以正常工作:

#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++ -std=c++11 test.cpp 编译,使用 G++ 版本:

g++ (Ubuntu 5.3.0-1ubuntu1~14.04) 5.3.0 20151204

考虑一下,我可以理解这里有两种类型在起作用:引用类型和被引用的类型。引用的类型是const,所以第二种情况是有意义的。对于第一种情况,如果引用的类型是const,我希望它要么返回,要么总是返回true,因为引用AFAIK不能“重新分配”。

为什么它会返回false

【问题讨论】:

    标签: c++ c++11 typetraits


    【解决方案1】:

    结果是正确的。

    引用永远不会是const,因为它们不能是cv-qualified。您说它们不能被重新分配是正确的(因此在某种意义上是不可变的),但这与 const-qualified 不同。

    如果你得到true 纯粹是因为referentconst,那么在所有其他情况下,这将与is_const 的含义完全不一致。例如,考虑指针。 is_const&lt;int const*&gt;::value 应该是什么?

    【讨论】:

    • 感谢您的回答。指针的例子真的很成功!
    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2015-03-13
    • 1970-01-01
    • 2012-08-09
    • 2015-02-27
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多