1. Paweł T
  2. hasMember

Source

hasMember /

Filename Size Date modified Message
965 B
3.5 KB
2.4 KB
37 B
1.8 KB

hasMember

Inspect C++ types with just one constexpr:

struct A{
  int foo;
};
struct B{};

static_assert(hasMember<A>(MEMBER_CHECKER_XOR(foo)) == 1, "Type 'A' doesn't have foo.");
static_assert(hasMember<B>(MEMBER_CHECKER_XOR(foo)) == 0, "Type 'B' has foo.");

This "micro library" also contains very simple, but useful implementation of "static if":

template <class T>
int getFoo(const T& t2, const char* name){
  constexpr auto L = Checker(foo); 
  return static_if_<hasMember(t2, MEMBER_CHECKER_XOR(foo))>(
    [=](auto t){
      std::cout << name << " have foo\n";
      return t.foo;
    },
    [=](auto t){
      std::cout << name <<" doesn't have foo\n";
      return 0;
    },
    t2
  );
}

A a; a.foo = 1;
B b; // notice B doesn't have foo
assert(getFoo(a, "A") == 1);
assert(getFoo(b, "B") == 0);

How to build

make

Compiler with C++14 support is required.