decltype返回一个实例的声明类型,或者是一个表达式的返回值类型。
语法:
decltype(entity)
decltype(expression)
如果参数是未括号化的id表达式或未括号化的类成员访问表达式,则decltype会产生此表达式命名的实体的类型。 如果没有这样的实体,或者参数指定了一组重载函数,则程序格式错误。
代码用例如下:
#include<iostream>
#include<type_traits>
using namespace std;
struct A {double x;};
const A* a;
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u){
return t + u;
}
int main()
{
int i = 22;
decltype(i) j = i*2;
cout<<"type(i) == type(j) ?" << boolalpha << is_same_v<decltype(i), decltype(j)> <<'\n';
cout<< "i=" <<i <<", " << "j="<<j<<endl;
auto f = [](int a, int b) -> int{
return a * b;
};
decltype(f) g = f;
i = f(2, 2);
j = f(3, 3);
cout<< "i=" <<i <<", " << "j="<<j<<endl;
return 0;
}