为什么 `std::is_const_v` 的行为不如预期?

Why does `std::is_const_v` not behave as expected?

#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没有按预期表现?

当类型为引用时,

std::is_constfalse

cppreference:

If T is a reference type then is_const<T>::value is always false. The proper way to check a potentially-reference type for const-ness is to remove the reference: is_const<typename remove_reference<T>::type>

在您的特定情况下,T 是转发引用,在传递左值参数时将推导为左值引用。这就是为什么您会在两种情况下看到 false