链接:(1条消息) C++怎么判断一个类存在指定的函数名的函数_写了程序换酒钱的博客-CSDN博客

1.使用宏来包含模版,这里主要考虑到模版不能成为虚函数,所以这里只是单纯的复制能力。即宏定义中可以定义模板,但不能直接使用当前定义的。
为此,可以改成如下方法:
-
- template<typename T, void(T::* )() = &T::show>
- void str(typename std::enable_if
::value, T>::type& t) { t.show(); }; -
- #define CheckType(x) \
- str
(x); -
- class A
- {
- public:
- void show()
- {
- cout << "123" <
- }
- };
-
- int main()
- {
- A a;
- CheckType(a);
- }
方法一:

方法二:

可以进行其他的判断处理,包括如果没有这个函数,则处理成其他方法。

- #define HAS_MEMBER(member)\
- template
struct has_member_##member\ - {\
- private:\
- template
static auto Check(int) -> decltype(std::declval().member(std::declval ()...), std::true_type()); \ - template
static auto Check(...) -> decltype(std::false_type()); \ - public:\
- static const bool value = std::is_same
(0)), std::true_type>::value; \ - }; \
- HAS_MEMBER(show);
- #define Testt(x) \
- has_member_show
::value?x.show():void(); -
- class A
- {
- public:
- void show()
- {
- cout << "123" << endl;
- }
- };
-
- int main()
- {
- A a;
- Testt(a);
- }
其中重点:
0:decltype 用逗号表达式进行赋值操作。
1:此处说明类中的成员函数可以用(.函数名)进行判断是否存在
2:Check(0),此处以先判断Check(int)方法,如果不符合,就会去判断Check(...).
3:void()可以代表空处理。
4:template void(T::* )() = &T::show> ,void(T::* )() = &T::show表可以表示类中指定的某函数名称。