- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我遇到一个问题,我需要发现两种类型(具有一个或零个基类)的共同祖先(如果存在)。是否有可能建立一个类型特征来解决这个问题?在代码中:
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 {};
现在,child12
和 child21
有两个共同的祖先:root1
和 root2
...哪个是最近的?
它们是等价的。考虑一下我添加:
struct root3 {}; struct child31: root3, child1 {};
然后root1
是child12
的共同祖先, child21
和 child31
.
但是如果我绕过 closest_common_ancestor
的定义并任意定义closest_common_ancesotr<child12, child21>
是root2
, 然后我找不到与 child31
的任何共同祖先.
因此,我的建议是列出所有最近的祖先,并使用 tuple
实现集合操作。
关于c++ - 如何在编译时推断出两种类型共有的继承树的根(如果存在)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8000885/
基础问题 我要解决的基本问题是: 我有一个模板参数包 ArgTypes,我需要用包装在 std::optional 中的每个类型创建一个元组。例如:make_optional_tuple应该返回 st
我使用 createEntityAdapter 设置了一个简单的 redux store。初始状态包含实体、ID、状态、错误设置等 const carouselEventAdapter = creat
我有一些(遗留)代码,如下所示: void castFoo(string type, void* foo) { FooA* foo_a = NULL; FooB* foo_b = NULL;
我的代码是 const int *const ptrA = nullptr; auto *ptrB = &ptrA; 我对 const int *const ptrA 的看法是: (*
我目前正在尝试用 C++ 实现 XOR 链表。我尝试使用模板使其通用。编译时会弹出此错误,我无法解决这个问题。 我尝试使用模板在谷歌上搜索 XOR 链表,但到目前为止似乎还没有实现它。 异或链表.h:
我正在尝试找到一种方法来调用多个类成员函数,每个函数都有不同的参数,并且在调用前后会发生某些已知功能。 这个包装函数是我试过的,但是例如对它的最终调用不会编译错误: 'bool Wrapper(Wor
此代码在 上编译成功g++ ( Coliru ) ,但不是 Visual C++ ( rextester ) - 在线和我的桌面。 它是一个更大的 Visual Studio 2015 项目的简化版本
我正在尝试编写一个通用类,它传递一个键 key 对应于一组已知接口(interface)中的一个的键,稍后可以传递一个对象 thing 并类型安全地访问 thing[key]。这是我得到的: inte
关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。 这个问题是由于错别字或无法再重现的问题引起的。虽然类似的问题可能是on-topi
我是一名优秀的程序员,十分优秀!