Possible Duplicate:
Is it possible to write a C++ template to check for a member-function's existence?
I need a way to decide if a template class has some member function, so that I can call different specializations for a functions. For example, I have the following classes:
class A1 {
void a() const { cout << "a1" << endl; }
};
class A2 {
void a() const { cout << "a2" << endl; }
};
class B {
void b() const { cout << "b" << endl; }
};
When I call my function with an instance of A1 or A2 as the template parameter, I want to call one overload (which can utilize a()
), but if it doesn't exist, I can go without it.
I was looking at the standard and Boost type traits libraries, but found nothing like this. I basically want something like this:
template <class T>
typename enable_if<has_member<A, a>::value>::type
f(const T& t) {
t.a();
}
template <class T>
typename enable_if<!has_member<A, a>::value>::type
f(const T&) {
cout << "no a" << endl;
}
The problem is that I don't know of any has_member
type traits, and I don't know how to implement it.