C++如何判断一个类型是否包含某个函数从而选择性的运行?

您所在的位置:网站首页 c++怎么判断类型 C++如何判断一个类型是否包含某个函数从而选择性的运行?

C++如何判断一个类型是否包含某个函数从而选择性的运行?

2022-05-28 22:51| 来源: 网络整理| 查看: 265

在我这边,题目中的 _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; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3