Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the class has any base class in C++ in compile time

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!

like image 378
Netherwire Avatar asked Nov 30 '25 02:11

Netherwire


1 Answers

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;
}
like image 118
marcos assis Avatar answered Dec 02 '25 16:12

marcos assis