我试图了解以下类模板的工作原理(取自此处),但我无法正确理解:
template <typename Type>
class has_member
{
class yes { char m;};
class no { yes m[2];};
struct BaseMixin
{
void operator()(){}
};
struct Base : public Type, public BaseMixin {};
template <typename T, T t> class Helper{};
template <typename U>
static no deduce(U*, Helper<void (BaseMixin::*)(), &U::operator()>* = 0);
static yes deduce(...);
public:
static const bool result = sizeof(yes) == sizeof(deduce((Base*)(0)));
};
更具体地说,我不明白其中的目的BaseMixin
和存在operator()
。另外,既然Base
是从它派生的,我也不明白。
更具体地说,当模板参数Type
已定义时operator()
,为什么只有SFINAE 被触发,导致第一个deduce()
函数被忽略而选择第二个函数?
无论如何,这是我的测试代码:
struct A{}; //SFINAE is triggered for A
struct B{ void operator()(){} }; //SFINAE is not triggered for B
struct C{ void operator()(int,int){} }; //SFINAE is not triggered for C
int main()
{
std::cout << std::boolalpha; //enable true/false instead of 1/0!
std::cout << has_member<A>::result << std::endl;
std::cout << has_member<B>::result << std::endl;
std::cout << has_member<C>::result << std::endl;
}
输出(ideone):
false
true
true