Get the Type of a Parent

℡╲_俬逩灬. 提交于 2019-12-02 08:22:11

问题


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?


回答1:


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.




回答2:


Just take the type as your argument:

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

}

bar is a Child that inherits from T. You can even add a separate overload for non-Child:

template <typename NonChild>
void foo(const NonChild& baz) { }


来源:https://stackoverflow.com/questions/31429363/get-the-type-of-a-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!