How to find if a method of a particular prototype exists inside a class?

心不动则不痛 提交于 2019-12-05 10:20:52

Why I'm getting the invalid parameter type 'void' error in the struct sMemberMethodChecker?.

Why the code is valid in MSVC but it isn't in GCC?.

I believe that MSVC is being helpful however GCC is being stringent in this particular code. As it's somehow not allowing Return (Type::*)(void). However one need to dig it more to know the exact reason.

Is this code no-standard?.

Can't say until it doesn't compile. And searching standard for the features like SFINAE is not everyone's cup of tea.

Is the SFINAE trickery exclusive of C++11?

Not at all. SFINAE existed before C++11.
Here is the simplified way of what you want to do:

template<typename ClassName, typename ClassMethodType>
struct HasMethod
{
  template<typename Type, Type Object> struct Contains;
  typedef char (&yes)[2];

  template<typename Class, typename MethodType>
  static yes Check (Contains<MethodType, &Class::size>*);
  template<typename Class, typename MethodType>
  static char Check (...);

  static const bool value = (sizeof(Check<ClassName,ClassMethodType>(0)) == sizeof(char));
};

HasMethod<ClassName, ClassMethodType>::value gives you the answer if a certain type member method exists inside it or not.
As of now HasMethod<> is exclusive to the method naming size with user provided type. But you can create a macro for above code and make the function name configurable.

Here is a working demo with g++.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!