Skip to content

Instantly share code, notes, and snippets.

@gium
Created July 7, 2011 14:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gium/1069605 to your computer and use it in GitHub Desktop.
Save gium/1069605 to your computer and use it in GitHub Desktop.
C++ traits to know if a type has a method.
#include <iostream>
#include <vector>
#include <list>
#include <set>
template <typename T>
struct HasPushBack {
typedef char yes[1];
typedef char no[2];
template <class U, void (U::*)(const typename U::value_type &) = &U::push_back> struct MethodTraits;
template <typename U>
static yes& _has(MethodTraits<U>*);
template <typename>
static no& _has(...);
static const bool value = sizeof (_has<T>(0)) == sizeof (yes);
};
int main() {
std::clog << HasPushBack<int>::value << std::endl;
std::clog << HasPushBack<std::vector<int> >::value << std::endl;
std::clog << HasPushBack<std::list<int> >::value << std::endl;
std::clog << HasPushBack<std::set<int> >::value << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment