Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?
Here's a simple example of what I would want to write:
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
So, if class T
has toString()
defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.
Best Answer
Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code:
I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.