Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get base class for a type in class hierarchy

Tags:

c++

c++11

Is is possible to get base class type in a class hierarchy?

For example:

struct A{};
struct B{} : public A;
struct C{} : public B;

I want some template that will have typedef Base<T>::Type inside like this:

Base<A>::Type == A
Base<B>::Type == A
Base<C>::Type == A

Is this possible? What about the case when I have multiple inheritance?

like image 279
Mircea Ispas Avatar asked Apr 28 '13 11:04

Mircea Ispas


People also ask

How do you identify a base class and a derived class?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.

Can a class inherit from multiple base classes?

You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance. The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.

What is the base class of a base class?

What is a Base Class? In an object-oriented programming language, a base class is an existing class from which the other classes are determined and properties are inherited. It is also known as a superclass or parent class.

Can struct be used as base class for inheritance?

Yes, struct can inherit from class in C++. In C++, classes and struct are the same except for their default behaviour with regards to inheritance and access levels of members.


2 Answers

Classes in C++ can have more than one base class, so there's no sense in having a "get me the base" trait.

However, the TR2 additions include new compiler-supported traits std::tr2::bases and std::tr2::direct_bases, which returns an opaque type list of base classes.

I'm not sure whether this will make it into C++14, or whether it'll be released independently, but GCC already seems to support this.

like image 162
Kerrek SB Avatar answered Oct 04 '22 15:10

Kerrek SB


I think std::is_base_of can help you

#include <type_traits>

std::is_base_of<B, D>()

If D is derived from B or if both are the same non-union class, provides the member constant value equal to true. Otherwise value is false.

You can use it to check if a class is base class of another or not :

std::is_base_of<A, A>()   // Base<A>::Type == A

std::is_base_of<A, B>()   // Base<B>::Type == A

std::is_base_of<A, C>()   // Base<C>::Type == A
like image 33
masoud Avatar answered Oct 04 '22 16:10

masoud