本文,
引用http://blog.csdn.net/godcupid/article/details/50420925
引用http://blog.csdn.net/freeelinux/article/details/53429009
对以上原作者表示感谢。
SFINAE:Substitution Failure Is Not An Error,替代失败不是错误。
个人总结:
在调用某个函数时,编译器有多个重载函数可供选择,如果首先找到的是不匹配的版本,不会宣告失败,而是继续寻找,找到并使用最匹配的版本。(要是到最后也没找到合适的版本,就只好宣告失败了。)
举例一:
以下代码,依次取消一个#number注释,编译和运行一次,发现匹配度从上到下,#3有最高匹配度。
#include<iostream>
class MyClass{};
void call(MyClass c)
{
std::cout << "MyClass" << std::endl;
}
//#1
//void call(...)
//{
// std::cout << "..." << std::endl;
//}
//#2
//void call(float n)
//{
// std::cout << "float" << std::endl;
//}
//#3
//void call(int n)
//{
// std::cout << "int" << std::endl;
//}
int main()
{
call(1);
return 0;
}
所以,可以利用这种特性进行特性提取,比如判断一个【类型】有没有某种【成员类型】,判断一个【类型】有没有某种【成员函数 】,以下是成员类型的判断:
#include<iostream>
using namespace std;
struct foo1 {
typedef float foobar;
};
struct foo2 {
};
template <typename T>
struct has_typedef_foobar {
typedef char yes[1]; //一个字节的返回类型
typedef char no[2]; //二个字节的返回类型
//可能匹配一;
template <typename C>
static yes& test(typename C::foobar*) {}; //C::foobar*,这里的'*'号不能去掉,如果去掉,必须传入(此类型的)变量->这个函数才会成立,然而变量在编译期变量是不会真有的;
//改为指针则不需要变量,可以为空(NULL,0,nullptr)就能匹配。
//可能匹配二;
template <typename C>
static no& test(...) {};
//计算,实际匹配函数的返回类型大小,分别出有或没有这个变量.
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
int main()
{
cout << has_typedef_foobar<foo1>::value << endl; //false
cout << has_typedef_foobar<foo2>::value << endl; //true
return 0;
}
以下是成员函数判断:
#include<iostream>
#include<typeinfo>
struct A {};
struct B
{
std::string serialize() const
{
return "I am a B!";
}
};
struct C
{
std::string serialize;
};
template <class T> struct hasSerialize
{
// For the compile time comparison.
typedef char yes[1];
typedef char no[2];
template <typename U, U u> struct reallyHas;
template <typename C> static yes& test(reallyHas<std::string(C::*)(), &C::serialize>* /*unused*/) { }
template <typename C> static yes& test(reallyHas<std::string(C::*)() const, &C::serialize>* /*unused*/) { }
template <typename> static no& test(...) { }
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
int main()
{
std::cout << hasSerialize<A>::value << std::endl;
std::cout << hasSerialize<B>::value << std::endl;
std::cout << hasSerialize<C>::value << std::endl;
return 0;
}