c++11总结17——decltype

1. 语法

decltype ( expression )

decltype(declare type)用于查询表达式的类型,即编译时期进行自动类型推导。如上所示,该语句返回expression表达式的类型。

注意:decltype仅仅是查询表达式的类型,并不会对表达式求值。

2. 推导规则

1)如果 expression是一个不被括号( )包围的表达式,或者是一个类成员访问表达式,或者是一个单独的变量,那么 decltype(exp) 的类型就和 exp 一致,这是最普遍最常见的情况。

2)如果 expression是函数调用,那么 decltype(exp) 的类型就和函数返回值的类型一致。

3)如果 expression是一个左值,或者被括号( )包围,那么 decltype(expression) 的类型就是 expression的引用;假设 expression的类型为 T,那么 decltype(expression) 的类型就是 T&。

3. auto与decltype

auto varname = value;
decltype(exp) varname = value;

1)auto 根据=右边的初始值 value 推导出变量的类型,而 decltype 根据 exp 表达式推导出变量的类型,跟=右边的 value 没有关系;

2)auto 要求变量必须初始化,而 decltype 不要求,即可以写成这样“decltype(exp) varname;”;

4. 基本使用

const int&& foo();
int i;
struct A { double x; };
const A* a = new A();

decltype(foo())  x1 = 1;  // const int&&      (1)
decltype(i)      x2;      // int              (2)
decltype(a->x)   x3;      // double           (3)
decltype((a->x)) x4 = 1;  // double&          (4)

5. 实例

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

struct A { double x; };
const A* a;

decltype(a->x) y;       // type of y is double (declared type)
decltype((a->x)) z = y; // type of z is const double& (lvalue expression)

template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) // return type depends on template parameters
									  // return type can be deduced since C++14
{
	return t + u;
}

int main()
{
	int i = 33;
	decltype(i) j = i * 2;

	std::cout << "i and j are the same type? " << std::boolalpha
		<< std::is_same_v<decltype(i), decltype(j)> << '\n';

	std::cout << "i = " << i << ", "
		<< "j = " << j << '\n';

	auto f = [](int a, int b) -> int
	{
		return a * b;
	};

	decltype(f) g = f; // the type of a lambda function is unique and unnamed
	i = f(2, 2);
	j = g(3, 3);

	std::cout << "i = " << i << ", "
		<< "j = " << j << '\n';

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/www_dong/article/details/114808127
今日推荐