C++

Asked • 09/28/19

Is it possible to write a template to check for a function's existence?

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.

1 Expert Answer

By:

Patrick B. answered • 10/05/19

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.