感谢C 14,我们很快就能够减少冗长的尾随返回类型;例如David Abrahams 2011
post的通用最小例子:
- template <typename T,typename U>
- auto min(T x,U y)
- -> typename std::remove_reference< decltype(x < y ? x : y) >::type
- { return x < y ? x : y; }
在C 14下,可以省略返回类型,并且min可以写为:
- template <typename T,U y)
- { return x < y ? x : y; }
这是一个简单的示例,但是返回类型推导对于通用代码非常有用,并且可以避免很多复制.我的问题是,对于这样的功能,我们如何整合SFINAE技术?例如,我如何使用std :: enable_if来限制我们的min函数返回积分的类型?
解决方法
如果您使用返回类型扣除,则不能使用返回类型SFINAE函数.这在
proposal中提到
Since the return type is deduced by instantiating the template,if the instantiation is ill-formed,this causes an error rather than a substitution failure.
但是,您可以使用额外的未使用模板参数来执行SFINAE.
- template <class T,class U>
- auto min1(T x,U y)
- { return x < y ? x : y; }
- template <class T,class U,class...,class = std::enable_if_t<std::is_integral<T>::value &&
- std::is_integral<U>::value>>
- auto min2(T x,U y)
- {
- return x < y ? x : y;
- }
- struct foo {};
- min1(foo{},foo{}); // error - invalid operands to <
- min1(10,20);
- min2(foo{},foo{}); // error - no matching function min2
- min2(10,20);