c++ - Is it possible to write a template to check for a function's existence? -
is possible write template changes behavior depending on if member function defined on class?
here's simple example of want 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, uses it; otherwise, doesn't. magical part don't know how "function_exists" part.
yes, sfinae can check if given class provide method. here's working code:
#include <iostream> struct hello { int helloworld() { return 0; } }; struct generic {}; // sfinae test template <typename t> class has_helloworld { typedef char one; typedef long two; template <typename c> static 1 test( typeof(&c::helloworld) ) ; template <typename c> static 2 test(...); public: enum { value = sizeof(test<t>(0)) == sizeof(char) }; }; int main(int argc, char *argv[]) { std::cout << has_helloworld<hello>::value << std::endl; std::cout << has_helloworld<generic>::value << std::endl; return 0; }
i've tested linux , gcc 4.1/4.3. don't know if it's portable other platforms running different compilers.
Comments
Post a Comment