对于const的引用,std :: is_const的等价物是什么?

Cla*_*diu 21 c++ types const

考虑一下代码:

int const  x = 50;
int const& y = x;
cout << std::is_const<decltype(x)>::value << endl; // 1
cout << std::is_const<decltype(y)>::value << endl; // 0
Run Code Online (Sandbox Code Playgroud)

这是有道理的,因为y不是const参考,它是对a的引用const.

有没有foo这样std::foo<decltype(y)>::value的1?如果没有,那么定义我自己的是什么样的呢?

Bor*_*der 18

使用remove_reference:

#include <string>
#include <iostream>
#include <type_traits>
using namespace std;

int main()
{
    int const  x = 50;
    int const& y = x;
    cout << std::is_const<std::remove_reference<decltype(x)>::type>::value << endl; // 1
    cout << std::is_const<std::remove_reference<decltype(y)>::type>::value << endl; // 1

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

见coliru

  • 如果T不是引用,则remove_reference无效,如文档中所述. (2认同)