Skip to content

Instantly share code, notes, and snippets.

@fenbf
Last active February 24, 2021 04:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fenbf/42795580abdee063ba0c to your computer and use it in GitHub Desktop.
Save fenbf/42795580abdee063ba0c to your computer and use it in GitHub Desktop.
template <typename T>
class HasToString
{
private:
typedef char YesType[1];
typedef char NoType[2];
template <typename C> static YesType& test( decltype(&C::ToString) ) ;
template <typename C> static NoType& test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(YesType) };
};
@Bab64
Copy link

Bab64 commented Oct 10, 2019

Hi fenbf. Thanks for this interesting solution. There is something that I'm not able to understand: 'test(0)'
In my understanding, the two 'test' functions have NO BODY. How then you may call with any of them with '0'? Why an int. Beyond, if I use '1' instead of '0', the global program does not work at all? Thanks in advance for any highlight!

@fenbf
Copy link
Author

fenbf commented Oct 10, 2019

Hi! we don't need bodies of the functions as it's used only at compile time. So we "Call" them without running the code... "0" converts to nullp pointer and that matches with the member function pointer &C::ToString. But if the ToString function is not available then we call default "NoType test(...) that matches all params.
You can also have a look at my updated post, with C++17 techniques: https://www.bfilipek.com/2019/07/detect-overload-from-chars.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment