gpt4 book ai didi

c++ - 如何在编译时推断出两种类型共有的继承树的根(如果存在)?

转载 作者:可可西里 更新时间:2023-11-01 16:38:58 25 4
gpt4 key购买 nike

我遇到一个问题,我需要发现两种类型(具有一个或零个基类)的共同祖先(如果存在)。是否有可能建立一个类型特征来解决这个问题?在代码中:

template<typename T1, typename T2>
struct closest_common_ancestor
{
typedef XXX type; // what goes here?
};

给定以下类型:

struct root {};
struct child1 : root {};
struct child2 : root {};
struct child3 : child2 {};
struct unrelated {};

closest_common_ancestor 将产生以下类型:

closest_common_ancestor<root, child1>::type == root
closest_common_ancestor<child1, child2>::type == root
closest_common_ancestor<child3, child1>::type == root
closest_common_ancestor<child3, child2>::type == child2
closest_common_ancestor<unrelated, child1>::type == error

我相信我可以解决这个问题,如果我可以检查一个类型是否有零个或一个基类,如果有的话,该类型的名称。这可能吗?

最佳答案

正如 K-ballo 所提到的,不幸的是不可能获得一个类(class)的基地列表(太糟糕了......)。

如果您手动注释您的类(例如,定义一个简单的 std::tuple<> 列出碱基),那么您可以使用此信息。当然,更简单的方法是使用特征:

template <typename> struct list_bases { typedef std::tuple<> type; };

然后你可以为你的类型专门化这个特征:

template <> struct list_bases<child1> { typedef std::tuple<root> type; };

从那里开始,您可以开始尝试寻找祖先……但它可能不是立竿见影的。除了实现细节(递归获取基数,实现“距离”选择)之外,我预计会出现“奇怪”情况的问题。

在通常的(线性)继承层次结构中,距离选择可以通过使用 is_base_of 的组合来解决。和 is_same ,但是请考虑以下层次结构:

struct root1 {}; struct root2 {};

struct child1: root1 {}; struct child2: root2 {};

struct child12: root1, child2 {}; struct child21: root2, child1 {};

现在,child12child21有两个共同的祖先:root1root2 ...哪个是最近的?

它们是等价的。考虑一下我添加:

struct root3 {}; struct child31: root3, child1 {};

然后root1child12的共同祖先, child21child31 .

但是如果我绕过 closest_common_ancestor 的定义并任意定义closest_common_ancesotr<child12, child21>root2 , 然后我找不到与 child31 的任何共同祖先.

因此,我的建议是列出所有最近的祖先,并使用 tuple实现集合操作。

关于c++ - 如何在编译时推断出两种类型共有的继承树的根(如果存在)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8000885/

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