1.获知表达式类型: 在编译期完成类型推导
decltype(expression) 很像sizeof用来推导表达式类型大小
int x = 10;
decltype(x) y = 1; // y->int
decltype(x + y) z = 0; // z->int
const int& i = x;
decltype(i) j = y; // j->const int&
与auto的不同之处:decltype 不会像auto在某种情况下会抛弃cv限定符,保留cv限定符!
2.实际应用:
1) 用于泛型编程:
template <class ContainerT>
class Foo
{
typename ContainerT::iterator it_; //此处可能会出现error
public:
void func(ContainerT& container)
{
it_ = container.begin();
}
};
ContainerT::iterator不能包括所有迭代器类型,比如ContainerT是个const类型,就应当使用const_iterator;
正确方式:
typename decltype(ContainerT().begin()) it_;
2)通过变量表达式抽取变量类型,往往只关注变量本身,而不关心其具体类型,例如:
vector<int> v;
decltype(v)::value_type i = 0; // 只要知道v是个容器即可,后面而不需要出现vector<int>这样具体类型了
3.auto与decltype结合使用:返回类型后置(跟踪返回类型)
在泛型编程中,可能通过参数的运算来得到返回值类型。
template <typename R, typename T, typename U>
R add(T t, U u)
{
return t+u;
}
int a = 1; float b = 2.0;
auto c = add<decltype(a+b)>(a, b); // 缺点:冗长
template <typename T, typename U>
decltype(t + u) add(T t, U u)
{
return t+u; //error: **返回值是前置语法**,在返回值定义时, 参数变量t和u还不存在
}
template <typename T, typename U>
decltype(T() + U()) add(T t, U u)
{
return t+u; // 缺点:T 和 U可能没有无参构造函数
}
template <typename T, typename U>
decltype((*(T*)0) + (*(U*)0)) add (T t, U u)
{
return t+u; //缺点:晦涩,可读性低
}
正确:返回类型后置语法:
template <typename T, typename U>
auto add(T t, U u) ->decltype(t + u)
{
return t + u;
}