C++ 11 decltype 类型推导

// decltype.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
using namespace std;

class Foo 
{
public:
	static const int Number = 0;
	int x;
};

int& func_int_r(void);		
int&& func_int_rr(void);	
int func_int(void);

const int& func_cint_r(void);
const int&& func_cint_rr(void);
const int func_cint(void);

const Foo func_cfoo(void); 

template <class ContainerT>
class Sample
{
	decltype(ContainerT().begin()) it_;
public:
	void func(ContainerT& container)
	{
		it_ = container.begin();
	}
};
int main()
{
   // grammar
   // decltype(exp),it deduce the type in compiling time
	int x = 0;
	decltype(x) y = 1;			// y==>int
	decltype(x + y) z = 0;		// z==>int

	const int& i = x;
	decltype(i) j = y;			// j==>const int&

	const decltype(z)* p = &z;	// *p==>const int,p==>const int*
	decltype(z)*pi = &z;		// *pi==>int	,pi==>int*
	decltype(pi)*pp = &pi;		// *pp==>int*   ,pp==>int**

	//rules
	//1.exp is identify、class access expression,the decltype(exp) is same as exp type
	

	int n = 0;
	volatile const int & xx = n;
	decltype(n) a = n;			// a==>int
	decltype(xx) b = n;			// b==>const volatile int &
	decltype(Foo::Number) c = 0;// c==>const int

	Foo foo;
	decltype(foo.x) d = 0;		// d==>int, class access expresion

	//2.exp is a function invoke,decltype(exp) type is same as return type
	int xxx = 0;
	decltype(func_int_r()) a1 = xxx;	// a1==>int&
	decltype(func_int_rr()) b1 = 0;		// b1==>int&&
	decltype(func_int())	c1 = 0;		// c1==>int

	decltype(func_cint_r()) a2 = x;		// a2==>const int &
	decltype(func_cint_rr()) b2 = 0;	// b2==>const int&&
	decltype(func_cint())	 c2 = 0;	// c2==>int 

	decltype(func_cfoo())	ff = Foo();
	//3.other situation if exp is a left value,the decltype(exp) is exp type left reference,otherwise,same as exp type
	struct Test
	{
		int x;
	};
	const Test test = Test();
	decltype(test.x) mm = 0;		// m==>int
	decltype((test.x)) nn = mm;     // n==>const int &

	{
		int n = 0, m = 0;
		decltype(n + m) c = 0;		// c==>int
		decltype(n += m)  d = c;	// d==>int&
	}
}

/*
int& func_int_r(void) {
	
}
int&& func_int_rr(void) {
	
}
int func_int(void) {}

const int& func_cint_r(void) {}
const int&& func_cint_rr(void) {}
const int func_cint(void) {}

const Foo func_cfoo(void) {}

*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蚂蚁_CrkRes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值