本文介绍了获取父类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下类别:

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

我还有一个模板化功能:

I also have a templatized function:

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

做了一些模板体操后我有一节已确定 bar 的代码是某种 Child 。但我需要找到什么排序。

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.

我希望能够在栏上进行调用产生继承的类型。所以找到 Parent 类型的假句法将是:

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?

推荐答案

根据OP的要求,这是我上面评论的扩展版本:

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;
}

如果 T 是不能直接使用(例如,在lambda中),那么这应该有效:

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;
};

为了让它更好更短,

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;
};

(虽然 parent 是一个相对常见的名字;小心冲突。 parent_t ,也许?)

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

对于不受你控制的类型,如果类型集是已知的, parent< T> 也可以是外部类型特征。

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

这篇关于获取父类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 13:06