SFINAE示例不清楚

SFINAE example not clear

本文关键字:不清楚 SFINAE      更新时间:2023-10-16

http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error

#include <iostream>
template <typename T>
struct has_typedef_foobar {
    // Types "yes" and "no" are guaranteed to have different sizes,
    // specifically sizeof(yes) == 1 and sizeof(no) == 2.
    typedef char yes[1];
    typedef char no[2];
    template <typename C>
    static yes& test(typename C::foobar*);
    template <typename>
    static no& test(...);
    // If the "sizeof" the result of calling test<T>(0) would be equal to the sizeof(yes),
    // the first overload worked and T has a nested type named foobar.
    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
struct foo {    
    typedef float foobar;
};
int main() {
    std::cout << std::boolalpha;
    std::cout << has_typedef_foobar<int>::value << std::endl;
    std::cout << has_typedef_foobar<foo>::value << std::endl;
}

上例显示了SFAINE。

  • 这里我不明白为什么sizeof(yes(==1和sizeof(no(==2
  • 由于测试是静态功能,因此应该有一些测试函数的定义。但这里的代码编译良好没有定义测试功能

1(sizeof(char)被定义为等于1。由于yes是一个由一个字符组成的数组的typedef,所以它的大小必须是一。同样,由于no是一个由两个字符组成的数组的typedef,所以它的大小必须是2 * sizeof(char),也就是2。

2( 函数test从未被调用,因此定义是不必要的-sizeof运算符是一个编译时操作,因此编译器只查看具有指定模板参数的测试实例化的返回类型的大小。因为它没有被调用,所以定义是不必要的,类似于为了使类不可复制而使私有的未定义副本构造函数。