【问题标题】:Why does `std::is_const_v` not behave as expected?为什么 `std::is_const_v` 的行为不符合预期?
【发布时间】:2018-12-02 07:44:29
【问题描述】:
#include <iostream>
#include <type_traits>

using namespace std;

template<typename T>
void f(T&&)
{
    cout << boolalpha << std::is_const_v<T> << endl;
    cout << boolalpha << std::is_const_v<T&&> << endl;
}

int main()
{
    const int n = 1;
    f(n);
}

输出是:

false
false

这里,n 是一个明显的 const 变量,为什么 std::is_const_v 的行为不符合预期?

【问题讨论】:

    标签: c++ c++11 constants standards typetraits


    【解决方案1】:

    当类型为引用时,std::is_constfalse

    cppreference:

    如果T 是一个引用类型,那么is_const&lt;T&gt;::value 总是假的。检查潜在引用类型是否为 const 的正确方法是删除引用:is_const&lt;typename remove_reference&lt;T&gt;::type&gt;

    在您的具体情况下,T 是一个转发引用,在传递左值参数时将被推断为左值引用。这就是为什么您会在两种情况下看到false

    【讨论】:

      猜你喜欢
      • 2019-05-09
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多