问题描述
我想进入更多的模板元程序设计。我知道SFINAE代表替代故障不是一个错误。
I want to get into more template meta-programming. I know that SFINAE stands for "substitution failure is not an error." But can someone show me a good use for SFINAE?
推荐答案
下面是一个例子():
template<typename T>
class IsClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
// Will be chosen if T is anything except a class.
template<typename C> static Two test(...);
public:
enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
当 IsClassT< int> :: Yes
因为int不是一个类,所以它不能有一个成员指针,因此不能转换为 int int :: *
。如果SFINAE不存在,那么你会得到一个编译器错误,像'0不能转换为非类型int的成员指针。相反,它只是使用返回Two的 ...
形式,因此求值为false,int不是类类型。
When IsClassT<int>::Yes
is evaluated, 0 cannot be converted to int int::*
because int is not a class, so it can't have a member pointer. If SFINAE didn't exist, then you would get a compiler error, something like '0 cannot be converted to member pointer for non-class type int'. Instead, it just uses the ...
form which returns Two, and thus evaluates to false, int is not a class type.
这篇关于C ++ SFINAE示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!