在我这边,题目中的 _HAS_FUNC 实现不能判断是否含有方法,总是返回 false_type printf("%d\n", _HAS_FUNC::value);
printf("%d\n", _HAS_FUNC::value);
都是返回 0。 #include
#include
#define TYPE_HAS_MEM_FUNC(class_name, func) \
template \
struct class_name { \
typedef char yes; \
typedef void* no; \
\
template \
static yes check(decltype(&C::func)); \
template \
static no check(...); \
\
public: \
enum { value = sizeof(check(0)) == sizeof(yes) }; \
};
TYPE_HAS_MEM_FUNC(HasFun, fun)
template
struct Int2Type {
enum { value = v };
};
////////////////////////////////////////////////////////
template
static void __call_fun_impl(T&& a, Int2Type) {
a.fun();
}
template
static void __call_fun_impl(T&& a, Int2Type) {
a.other_fun();
}
template
static void call_fun(T&& a) {
typedef typename std::remove_reference::type T_;
__call_fun_impl(std::forward(a), Int2Type());
}
class TestA {
public:
void fun() {
printf("TestA::fun()\n");
}
};
class TestB {
public:
void other_fun() {
printf("TestB::other_fun()\n");
}
};
int main(int argc, char** argv) {
call_fun(TestA());
call_fun(TestB());
TestA a;
TestB b;
call_fun(a);
call_fun(b);
return 0;
}
|