【发布时间】:2018-11-22 19:47:20
【问题描述】:
我有一个看起来像这样的类:
template<class KeyType, class... Types>
class BasicCompound
{
public:
using mapped_type = std::variant
<
ValueWrapper<BasicCompound>
, ValueWrapper<Types>...
>;
using key_type = KeyType;
// Accessors for retreiving and modifying content
// ...
private:
std::map<key_type, mapped_type> m_content;
};
ValueWrapper 决定将内容放入内联或std::unique_ptr。是否有可能使用类似的接口(可能通过某种代理)使递归成为可选?可选是指用户不应该自动获得将BasicCompound 存储在自身内部的可能性,而是在类型列表中指定它。
我想到的:
-
using指令不起作用。新类型不能在其自身中定义,并且不允许对后面的 typedef 进行预声明。 - 将
bool添加到类型列表中,并将std::conditional_t用于mapped_type。但是,如果用户想要存储X<BasicCompound>,则此方法会失败。 - 从外部注入
mapped_type。那我就不能隐藏ValueWrapper这个东西的使用了。 -
在
typdef上使用继承struct MyCompound : BasicCompound<std::string, MyCompound, int> {};这可行,但结构不是严格递归的,因为
MyCompound现在是与BasicCompound不同的类型。或许类似 CRTP 的方法可以解决这个问题,但是内部复合类型的处理方式必须与其他类型不同。
【问题讨论】:
标签: c++ recursive-datastructures