2

I want to check whether the class X has ANY base class using type utilities in C++.

For example:

class X : public Y
{
}
static_assert(std::has_base_class<X>::value, "") // OK

but:

class X
{
}
static_assert(std::has_base_class<X>::value, "") // Failed

Does anything like my imaginary has_base_class exist in the standard library? Thanks!

Netherwire
  • 2,669
  • 3
  • 31
  • 54

1 Answers1

4

As mentioned in comments you can't do exactly this in standard C++. The closest you get from std library is std::is_base_of, but it is for testing a specific base class.

But as mentioned here GCC has std::tr2::bases (and std::tr2::direct_bases) that solves your question for a generic "has any base" assertion. These came from the N2965 proposal and unfortunately was rejected for std C++.

Here's a sample code showing how you can use this GCC extension to assert just what you want:

#include <tr2/type_traits>

class B {};

class X : public B {};
static_assert(std::tr2::bases<X>::type::empty(),"X");
// doesn't compile because X bases tuple returned is not empty

class Y {};
static_assert(std::tr2::bases<Y>::type::empty(),"Y");

#include <iostream>
using namespace std;

int main() {
  return 0;
}
marcos assis
  • 388
  • 2
  • 14