Skip to content

Instantly share code, notes, and snippets.

@preshing
Created January 3, 2018 21:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save preshing/dfc476fee9cedf54c065ac5d04b3f63d to your computer and use it in GitHub Desktop.
Save preshing/dfc476fee9cedf54c065ac5d04b3f63d to your computer and use it in GitHub Desktop.
Use SFINAE to call member function if present
#include <iostream>
class Foo {
public:
void bar() {
std::cout << "Foo::bar() called" << std::endl;
}
};
class Foo2 {
};
// callBarIfPresent(T*)
// This version will be called if T::bar() exists:
template <class T> auto callBarIfPresent(T* obj) -> decltype(obj->bar()) {
return obj->bar();
}
// This version will be called otherwise:
inline void callBarIfPresent(...) {
std::cout << "No member function called" << std::endl;
}
int main()
{
Foo foo;
callBarIfPresent(&foo);
Foo2 foo2;
callBarIfPresent(&foo2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment