在编译时查找基类 [英] Finding base class at compile time

查看:109
本文介绍了在编译时查找基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎说明了一切:在C ++中,有没有一种方法可以在编译时获取类的基本类型? IE.是否可以将一个类传递给模板,并让该模板使用将给定类的基础传递给它的其他模板?

The title almost says everything: Is there a way in C++ to get a class's base type(s) at compile time? I. e. is it possible to hand a class to a template, and let the template use other templates to which it hands the bases of the given class?

我的问题不是我自己是否可以实现这样的功能,我没有问题(使用特质等).我的问题是,是否有一些(模糊的)内置功能可用于此目的.

My question is not whether I can implement such a functionality myself, there is no question I can (using traits and the like). My question is whether there is some (obscure) builtin functionality that could be used to this end.

推荐答案

gcc支持此功能.参见

  • Kerrek's answer
  • tr2/type_traits
  • Andy Prowl's code example
  • n2965
  • What is the status of N2965 - std::bases and std::direct_bases?
  • How to query for all base classes of a class at compile time?

n2965提供了一个示例.

n2965 provides an example.

这个简单的例子说明了这些类型特征的结果.在 假设我们具有以下类层次结构:

This simple examples illustrates the results of these type traits. In the Suppose we have the following class hierarchy:

class E {};
class D {};
class C : virtual public D, private E {};
class B : virtual public D, public E {};
class A : public B, public C {};

因此,bases<A>::type is tuple<D, B, E, C, E>

类似地,direct_bases<A>::type is tuple<B, C>

Andy Prowl的代码示例如下:

Andy Prowl's code example is as follows:

#include <tr2/type_traits>
#include <tuple>

template<typename T>
struct dbc_as_tuple { };

template<typename... Ts>
struct dbc_as_tuple<std::tr2::__reflection_typelist<Ts...>>
{
    typedef std::tuple<Ts...> type;
};

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

int main()
{
    using namespace std;

    using direct_base_classes = dbc_as_tuple<tr2::direct_bases<C>::type>::type;

    using first = tuple_element<0, direct_base_classes>::type;
    using second = tuple_element<1, direct_base_classes>::type;

    static_assert(is_same<first, A>::value, "Error!");   // Will not fire
    static_assert(is_same<second, B>::value, "Error!");  // Will not fire
}

这篇关于在编译时查找基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆