3

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

I'm interested in finding some SFINAE-driven expressions that allow me to detect the presence of a member function and handle it accordingly, a la:

template <typename T>
int maybe_member(T& x, {{sfinae_1}})
{
    return x.maybe_member();
}

template <typename T>
int maybe_member(T& x, {{sfinae_2}})
{
    std::cerr << "This T does not implement maybe_member.\n";

    return 1;
}

int main()
{
    my_type_t instance;

    return maybe_member(instance);
}

A set of questions:

  • Can this be done in c++?
  • Does c++11 add anything to make this easier to implement?
Community
  • 1
  • 1
fbrereto
  • 35,429
  • 19
  • 126
  • 178
  • @LucTouraille: This is an **old** question that you linked though. And there are issues with the proposed solutions when applied to methods. A c++11 review that also catter to methods of a base class would be welcome. – Matthieu M. Jun 27 '12 at 08:05
  • @MatthieuM: Xeo provided [a nice answer](http://stackoverflow.com/a/9154394/20984) that uses c++11 features (`decltype`) and works well with inherited member functions (AFAICT). However, it is a bit buried in the list of answers, probably because it has been posted a long time after the question was asked. – Luc Touraille Jun 27 '12 at 09:47
  • @LucTouraille: The problem with Xeo's answer is that it does not address the "fallback" case, how to activate a function only when the class *does not have* a member. – Matthieu M. Jun 27 '12 at 13:17
  • @MatthieuM.: Fair enough, if you think this question is likely to attract more up-to-date and constructive answers, I'm willing to vote to reopen. – Luc Touraille Jun 27 '12 at 13:32
  • See also http://stackoverflow.com/q/1966362/20984, which tackles the issue of inherited member functions. – Luc Touraille Jun 27 '12 at 13:40
  • @LucTouraille: Nice, especially the second answer with `decltype`. – Matthieu M. Jun 27 '12 at 14:15

0 Answers0