SFINAE 可以理解为一个缺省模板匹配,虽然模板匹配的时候会匹配任意类型,但是
在闭包内部也会是按照最佳匹配来的,当没有匹配上的时候会报编译错误,这样不符合我们的要求。再
怎么地也要能编译运行嘛。
#include <iostream>
#include <stdio.h>
using namespace std;
template <typename T>
struct has_typedef_foobar {
typedef char yes;
typedef int no;
template <typename C>// 偏特化匹配
static yes& test(typename C::foobar*);// has function
template <typename C>
static no& test(...);
static const bool value = sizeof(test<T>(nullptr)) == sizeof(yes);// 如果匹配到no& test(...);就是缺省匹配,
};
struct foo {
typedef float foobar;
};
int main()
{
cout<<std::boolalpha;
cout<<has_typedef_foobar<int>::value<<endl; //false
cout<<has_typedef_foobar<foo>::value<<endl; //true 有c::foobar成员
printf("yes size ########## %d.\n",sizeof(has_typedef_foobar<int>::yes));
printf("yes size ########## %d.\n",sizeof(has_typedef_foobar<foo>::no));
return 0;
}
其实上面就是一个偏特化匹配的过程,偏特化没匹配上的时候,匹配的是缺省类型,也就是最上面的偏特化模板。
匹配上的时候,匹配的指定类型的模板