了解SFINAE [英] Understanding SFINAE

查看:178
本文介绍了了解SFINAE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,SFINAE意味着替换失败不会导致编译错误,但只是从可能的重载列表中删除原型。

As far as I know, SFINAE means substitution failures do not result in compilation errors, but just remove the prototype from the list of possible overloads.

我做什么不明白:为什么是这个SFINAE:

What I do not understand: why is this SFINAE:

template <bool C, typename T = void> struct enable_if{};
template <typename T> struct enable_if<true, T> { typedef T type; };

但这不是?

template <bool C> struct assert;
template <> struct assert<true>{};



从我的理解,底层逻辑在这里是一样的。此问题出自对此答案的评论

推荐答案

在C ++ 98中,SFINAE使用返回类型或函数的虚拟参数参数

In C++98, SFINAE is done with either a return type or a function's dummy argument with default parameter

// SFINAE on return type for functions with fixed arguments (e.g. operator overloading)
template<class T>
typename std::enable_if< std::is_integral<T>::value, void>::type
my_function(T const&);

// SFINAE on dummy argument with default parameter for functions with no return type (e.g. constructors)
template<class T>
void my_function(T const&, std::enable_if< std::is_integral<T>::value, void>::type* = nullptr);

在这两种情况下, T 为了获得嵌套类型类型是SFINAE的本质。与 std :: enable_if 相反,您的 assert 模板不具有嵌套类型

In both cases, substution of T in order to get the nested type type is the essence of SFINAE. In contrast to std::enable_if, your assert template does not have a nested type that can be used in substitution part of SFINAE.

请参阅Jonathan Wakely的优秀 ACCU 2013演示更多细节和C ++ 11表达式SFINAE。其他(如@BartekBanachewicz在评论中指出的)现在也可以在函数模板默认参数中使用SFINAE。

See Jonathan Wakely's excellent ACCU 2013 presentation for more details and also for the C++11 expression SFINAE. Among others (as pointed out by @BartekBanachewicz in the comments) is is now also possible to use SFINAE in function template default arguments

// use C++11 default function arguments, no clutter in function's signature!
template<class T, class dummy = typename std::enable_if< std::is_integral<T>::value, void>::type>
void my_function(T const&);

这篇关于了解SFINAE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆