Skip to content

Instantly share code, notes, and snippets.

@maxattack
Created August 26, 2014 16:24
Show Gist options
  • Save maxattack/3cbe5fb741d2ec046e0a to your computer and use it in GitHub Desktop.
Save maxattack/3cbe5fb741d2ec046e0a to your computer and use it in GitHub Desktop.
Has Member Template
#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