Created
August 26, 2014 16:24
-
-
Save maxattack/3cbe5fb741d2ec046e0a to your computer and use it in GitHub Desktop.
Has Member Template
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 <type_traits> | |
#include <iostream> | |
#include <iomanip> | |
#define DECLARE_HAS_MEMBER(member) \ | |
\ | |
template < class T > \ | |
class HasMember_##member \ | |
{ \ | |
private: \ | |
using Yes = char[2]; \ | |
using No = char[1]; \ | |
\ | |
struct Fallback { int member; }; \ | |
struct Derived : T, Fallback { }; \ | |
\ | |
template < class U > \ | |
static No& test ( decltype(U::member)* ); \ | |
template < typename U > \ | |
static Yes& test ( ... ); \ | |
\ | |
public: \ | |
static constexpr bool RESULT = sizeof(test<Derived>(nullptr)) == sizeof(Yes); \ | |
}; \ | |
\ | |
template < class T > \ | |
struct has_member_##member \ | |
: public std::integral_constant<bool, HasMember_##member<T>::RESULT> \ | |
{ }; \ | |
DECLARE_HAS_MEMBER(draw); | |
struct drawable { | |
void draw() { } | |
}; | |
struct dribable { | |
void dribble() { } | |
}; | |
int main(int argc, char *argv[]) { | |
using namespace std; | |
cout << "drawable has draw()? " << has_member_draw<drawable>() << endl; | |
cout << "dribable has draw()? " << has_member_draw<dribable>() << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment