SFINAE与C 14返回式扣除

前端之家收集整理的这篇文章主要介绍了SFINAE与C 14返回式扣除前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感谢C 14,我们很快就能够减少冗长的尾随返回类型;例如David Abrahams 2011 post的通用最小例子:
  1. template <typename T,typename U>
  2. auto min(T x,U y)
  3. -> typename std::remove_reference< decltype(x < y ? x : y) >::type
  4. { return x < y ? x : y; }

在C 14下,可以省略返回类型,并且min可以写为:

  1. template <typename T,U y)
  2. { 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.

  1. template <class T,class U>
  2. auto min1(T x,U y)
  3. { return x < y ? x : y; }
  4.  
  5. template <class T,class U,class...,class = std::enable_if_t<std::is_integral<T>::value &&
  6. std::is_integral<U>::value>>
  7. auto min2(T x,U y)
  8. {
  9. return x < y ? x : y;
  10. }
  11.  
  12. struct foo {};
  13.  
  14. min1(foo{},foo{}); // error - invalid operands to <
  15. min1(10,20);
  16.  
  17. min2(foo{},foo{}); // error - no matching function min2
  18. min2(10,20);

Live demo

猜你在找的C&C++相关文章