C++ SFINAE 示例?

2021-12-13 00:00:00 templates metaprogramming c++ sfinae

我想进入更多模板元编程.我知道 SFINAE 代表替换失败不是错误".但是有人可以告诉我 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?

推荐答案

这里有一个例子 (从这里):

Heres one example (from here):

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::Yes 被求值时,0 不能转换为 int int::* 因为 int 不是一个类,所以它不能有一个成员指针.如果 SFINAE 不存在,那么您将收到编译器错误,例如0 无法转换为非类类型 int 的成员指针".相反,它只是使用返回两个的 ... 形式,因此计算结果为 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.

相关文章