gpt4 book ai didi

c++ - 是否有可能在运行时从 C++ 类声明中知道继承的数量?

转载 作者:行者123 更新时间:2023-11-28 04:10:36 25 4
gpt4 key购买 nike

给定这些类示例,

class A {};
class B : A {};
class C {};
class D : A, C {};
class E : D {};

该函数应返回类 A 的继承数为 0,而对于类 B、C、D 和 E,该函数应分别返回 1、0、2、1。

Note: The function shouldn't take account the whole inherited classes (for example, E takes D that is inherited from A and C indirectly, so it would has 3 but in my case I want to know the number of inheritances of the class in its declaration)

最佳答案

不幸的是,这还没有进入语言。有 std::direct_bases 提案但被拒绝:What is the status of N2965 - std::bases and std::direct_bases?

所以你需要自己动手 - 有很多方法可以解决这个问题,但例如它可能类似于以下内容:

#include <tuple>

class A{
public:
using bases = std::tuple<>;
};

class B:A{
public:
using bases = std::tuple<A>;
};

class C{
public:
using bases = std::tuple<>;
};

class D:A,C{
public:
using bases = std::tuple<A,C>;
};

class E:D{
public:
using bases = std::tuple<D>;
};

template <class T>
size_t count_bases() {
return std::tuple_size<typename T::bases>::value;
}

int main() {
return count_bases<D>();//returns '2'
}

自己试试:https://godbolt.org/z/u0qoZa

关于c++ - 是否有可能在运行时从 C++ 类声明中知道继承的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57904271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com