0

Is there a trait that returns the base class of a specific class, with the assumption that there is no multiple inheritance involved? Basically something like:

struct Base
{

};

struct Derived : public Base
{

};

struct DerivedDerived : public Derived
{

};

static_assert(std::is_same_v<base<DerivedDerived>::type,Derived>);
static_assert(std::is_same_v<base<Derived>::type,Base>);
static_assert(std::is_same_v<base<Base>::type,Base>);
// with levels
static_assert(std::is_same_v<base<0,DerivedDerived>::type,Base>);
static_assert(std::is_same_v<base<1,DerivedDerived>::type,Derived>);
static_assert(std::is_same_v<base<2,DerivedDerived>::type,DerivedDerived>);
static_assert(std::is_same_v<base<0,Derived>::type,Base>);
static_assert(std::is_same_v<base<1,Derived>::type,Derived>);
lightxbulb
  • 1,251
  • 12
  • 29
  • You would have to inject that information yourself, something like `struct Derived : public GetBase {};` – super Oct 23 '19 at 13:18
  • @super Yeah, the idea was not to have to, otherwise, yes I can write type traits or do some hackery with crtp. – lightxbulb Oct 23 '19 at 13:19

1 Answers1

5

Nope. You can test whether a given type inherits from a given other type with std::is_base_of, but not ask for the base type outright. That is, until C++ gets static reflection sometime in the future.

Quentin
  • 62,093
  • 7
  • 131
  • 191