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 min2min2(10,20);
Live demo
总结以上是内存溢出为你收集整理的SFINAE与C 14返回式扣除全部内容,希望文章能够帮你解决SFINAE与C 14返回式扣除所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)