Используя SFINAE, я могу обнаружить, имеет ли данный класс определенную функцию членства. Но что, если я хочу протестировать на наследованные функции членства?
Следующее не работает в VC8 и GCC4 (т.е. обнаруживает это A
имеет функцию членства foo()
, но не это B
наследовал один):
#include
template
struct has_foo {
template struct type_check;
template static char (& chk(type_check*))[1];
template static char (& chk(...))[2];
static bool const value = (sizeof(chk(0)) == 1);
};
struct A {
void foo();
};
struct B : A {};
int main()
{
using namespace std;
cout << boolalpha << has_foo::value << endl; // true
cout << boolalpha << has_foo::value << endl; // false
}
Так, есть ли способ протестировать на наследованные функции членства?
Взгляните на эту тему:
http://lists.boost.org/boost-users/2009/01/44538.php
Полученный из кода, с которым связана эта дискуссия:
#include <iostream>
template <typename Type>
class has_foo
{
class yes { char m;};
class no { yes m[2];};
struct BaseMixin
{
void foo(){}
};
struct Base : public Type, public BaseMixin {};
template <typename T, T t> class Helper{};
template <typename U>
static no deduce(U*, Helper<void (BaseMixin::*)(), &U::foo>* = 0);
static yes deduce(...);
public:
static const bool result = sizeof(yes) == sizeof(deduce((Base*)(0)));
};
struct A {
void foo();
};
struct B : A {};
struct C {};
int main()
{
using namespace std;
cout << boolalpha << has_foo<A>::result << endl;
cout << boolalpha << has_foo<B>::result << endl;
cout << boolalpha << has_foo<C>::result;
}
Результат:
true
true
false