c++ - 在编译时查找基类

标签 c++ templates static-polymorphism

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

我的问题不是我是否可以自己实现这样的功能,毫无疑问我可以(使用特征等)。我的问题是是否有一些(晦涩的)内置功能可用于此目的。

最佳答案

gcc支持这一点。见

n2965 提供了一个例子。

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

It follows that bases<A>::type is tuple<D, B, E, C, E>

Similarly, direct_bases<A>::type is tuple<B, C>

Andy Prowl的代码示例如下:

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

关于c++ - 在编译时查找基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20798707/

相关文章:

c++ - 静态多态的Strategy和CRTP有什么区别?

c++ - 在构造对象之前使用对象成员

c++ - 在模板类中隐藏成员函数

C++ 删除 vector 中的对象

c++ - 模板特化中参数包的大小

c++ - 使用返回类型调用模板化成员指针函数时出错

c++ - 如果除法运算符未实现,则 SFINAE 回退

c++ - 是否有一种通用方法可以将函数模板改编为多态函数对象?

c++ - 使用构造函数初始化您的类,该构造函数将 std::map 作为带有大括号括起来的初始化程序的参数

c++ - 组合函数、绑定(bind)、C++ 和托管代码