0

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.

Community
  • 1
  • 1
petersohn
  • 10,129
  • 11
  • 54
  • 87
  • how and why do you need that? Couldn't you use template specialization for that, in a way that you do one version with calling a and another without calling a. and one of the template parameters shall distinguish which of the two you will actually take? – Alexander Oh Jul 14 '12 at 06:53

1 Answers1

-1

Use member detection idiom for that http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Member_Detector

Bartosz Przybylski
  • 1,526
  • 9
  • 14