decltype

文章目录

Defines a type equivalent to the type of an expression.

By using the decltype keyword, you can let the compiler find out the type of an expression, this is the realization of the often requested typepf feature.

One application of decltype is to declare return types; Another is to use it in metaprogramming or to pass the type of a lambda.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 1. declare return types
template<typename T1, typename T2>
decltype(x + y) add(T1 x, T2 y); // 不行

template<typename T1, typename T2>
auto add(T1 x, T2 y) -> decltype(x + y);

// 2. meta programming
template<typename T>
void test_decltype(T obj) {
map<string, float>::value_type elem1;
map<string, float> coll;
decltype(coll)::value_type elem2;

typedef typename decltype(obj)::iterator iType; // => typedef typename T::iterator iType
// test_decltype(complex<int>()) 编译失败

decltype(obj) anotherObj(obj);
}

// 3. pass the type of lambda
auto cmp = [](const Person& p1, const Person& p2) {
return p1.lastname() < p2.lastname() || (p1.lastname() == p2.lastname() && p1.firstname() < p2.firstname());
};
std::set<Person, decltype(cmp)> coll(cmp);