红魔咖啡馆

头发越掉越多,头发越掉越少

0%

【C++】decltype

decltype

用法

该运算符可以获得一个变量或表达式的值的类型

语法:decltype(变量\表达式)

用于变量时,可以获得变量类型、引用类型、cv限定符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int a = 3;
decltype(a) b = 5; // b的类型是int

const int a = 3;
decltype(a) b = 5; // b的类型是const int

int a = 3;
int& b = a;
decltype(b) c = a; // c的类型是int&

struct s{
    double a
};

decltype(s::a) a = 0.1; // a的类型是double
s t;
decltype(t.a) a = 0.1; // a的类型是double

用于表达式时:

1
2
3
4
5
6
7
8
9
int a;
decltype((a)) b = a; // b的类型是int&

string f1(){} // 返回string,是右值
string& f2(){} // 返回string&,是左值
string&& f3(){} // 返回string&&,是将亡值
decltype(f1()) s1; // b的类型是string
decltype(f2()) s2 = s1; // b的类型是string&
decltype(f3()) s3 = "hello"; // b的类型是string&&

即推导函数正好是函数的返回值类型

注意:decltype中的表达式仅用于编译时的类型推导,不会真正执行

decltype(auto)

decltype(auto) 变量 = 初始值表达式替换后等同于

decltype(初始值表达式) 变量 = 初始值表达式

此时表达式是可以执行的

value_category

该类模板可以推导出所给的值属于左值、纯右值还是将亡值

经典用法:将表达式的类别表达出来

1
2
#define VALUE_CATEGORY(expr) value_category<decltype((expr))>::value
#define CAT(a) std::cout <<"Category of "<< #a <<":"<<VALUE_CATEGORY(a)<<std::endl;

应用

常用于定义函数模板时,函数返回值的类型推到

1
2
3
4
5
6
template <typename T, typename U>
decltype(auto) add(T&& t, U&& u){
    return std::forward<T>(t)+std::forward<U>(u);
};

auto s = add(string("a"), string("b") )