Search code examples
c++inheritancetypesparentdecltype

Get the Type of a Parent


Given the following classes:

template <typename T>
class Child : public T {};

I also have a templatized function:

template <typename T>
void foo(const T& bar)

After doing some template gymnastics I have a section of code that has determined that bar is a Child of some sort. But I need to find of what sort.

I want to be able to make a call on bar that yields the type inherited. So fake syntax to find the type of Parent would be:

decltype(foo.parent) bar;

Is there any actual syntax to accomplish this?


Solution

  • As requested by the OP, here's an expanded version of my comment above:

    One common way of handling this if Child and its siblings are under your control is to add a nested type to them:

    template<typename T> class Child : public T 
    {
    public:
       using parent = T;
    };
    
    template<typename T> void foo(const T& bar)
    {
       typename T::parent goo;
    }
    

    If T is not directly available (in a lambda, for example), then this should work:

    auto foo2 = [](const auto& bar)
    {
       typename std::remove_reference_t<decltype(bar)>::parent goo;
    };
    

    To make it slightly nicer and shorter,

    template<typename T> using parent = typename T::parent;
    
    template<typename T> void foo(const T& bar)
    {
       parent<T> goo;
    }
    
    auto foo2 = [](const auto& bar)
    {
       parent<std::remove_reference_t<decltype(bar)>> goo;
    };
    

    (Although parent is a relatively common name; beware of clashes. parent_t, maybe?)

    For types that aren't under your control, if the set of types is known, parent<T> could also be an external type trait.