Jordi Espada
Jordi Espada

Reputation: 415

Is it possible to know the number of inheritances from a c++ class declaration at runtime?

Given these class examples,

class A {};
class B : A {};
class C {};
class D : A, C {};
class E : D {};

The function should return the number of inheritances of class A as 0 whereas for classes B, C, D and E this function should return 1, 0, 2, 1 respectively.

Note: The function shouldn't take account the whole inherited classes (for example, E takes D that is inherited from A and C indirectly, so it would has 3 but in my case I want to know the number of inheritances of the class in its declaration)

Upvotes: 0

Views: 100

Answers (1)

darune
darune

Reputation: 10972

Unfortunately, this hasn't entered the language yet. There were std::direct_bases proposal but it was rejected: What is the status of N2965 - std::bases and std::direct_bases?

So you need to roll you own - there are many ways you could go about this, but for example it could be something like the following:

#include <tuple>

    class A{
        public:
      using bases = std::tuple<>;
    };

    class B:A{
        public:
      using bases = std::tuple<A>;
    };

    class C{
        public:
      using bases = std::tuple<>;
    };

    class D:A,C{
        public:
      using bases = std::tuple<A,C>;
    };

    class E:D{
        public:
      using bases = std::tuple<D>;
    };

    template <class T>
    size_t count_bases() {
        return std::tuple_size<typename T::bases>::value;
    }

    int main() {
      return count_bases<D>();//returns '2'
    }

Try it yourself: https://godbolt.org/z/u0qoZa

Upvotes: 1

Related Questions