C++ - checking if a class has a certain method at compile time
- by jetwolf
Here's a question for the C++ gurus out there. Is there a way to check at compile time where a type has a certain method, and do one thing if it does, and another thing if it doesn't?
Basically, I have a template function
template <typename T>
void function(T t);
and I it to behave a certain way if T has a method g(), and another way if it doesn't.
Perhaps there is something that can be used together with boost's enable_if? Something like this:
template <typename T>
enable_if<has_method<T, g, void ()>, void>::type function(T t)
{
// Superior implementation calling t.g()
}
template <typename T>
disable_if<has_method<T, g, void ()>, void>::type function(T t)
{
// Inferior implementation in the case where T doesn't have a method g()
}
"has_method" would be something that preferably checks both that T has a method named 'g', and that the method has the correct signature (in this case, void ()).
Any ideas?