decltype关键字与返回类型后置

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值