How to call member function only if object happens to have it?

Viewed 7719

Possible Duplicate:
Is it possible to write a C++ template to check for a function's existence?

I have a function f that receives a value val of type T (templated). Is there any way to call a member function on val only if the type has such a member function?

Example:

struct Bar {
  void foo() const {}
};

template<class T>
void f(T const& val) {
  // Is there any way to call *only* if foo() is available on type T?                                                           
  // SFINAE technique?                                                                                                          
  val.foo();
}

int main() {
  Bar bar;
  f(bar);
  f(3.14);
}

Sounds like the SFINAE technique to me, maybe using boost::enable_if, but I don't know how to make it work here. Note that I can't easily change the Bar type in the example. I know it would be easy if Bar contained some certain typedef, etc., which signals that the function is available.

Needless to say, I don't know the set of types T that f will be called with. Some have the foo member function, some don't.

2 Answers
Related