Created
January 3, 2018 21:54
-
-
Save preshing/dfc476fee9cedf54c065ac5d04b3f63d to your computer and use it in GitHub Desktop.
Use SFINAE to call member function if present
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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