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?
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:If
T
is not directly available (in a lambda, for example), then this should work:To make it slightly nicer and shorter,
(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.Just take the type as your argument:
bar
is aChild
that inherits fromT
. You can even add a separate overload for non-Child
: