直接回答(见下文提示)
你可以使用make_recursive_variant做你想做的事:
Live On Coliru
#include <boost/variant.hpp>
#include <unordered_map>
struct LeafData {
int _i;
LeafData(int i) : _i(i) {}
}; // just for illustration
using LeafNode = std::unordered_map<std::string, LeafData>;
using Node = boost::make_recursive_variant<
LeafNode,
std::unordered_map<std::string, boost::recursive_variant_>
>::type;
using Inner = std::unordered_map<std::string, Node>;
int main() {
Node tree = Inner {
{ "a", LeafNode { { "one", 1 }, { "two", 2 }, { "three",3 } } },
{ "b", Inner {
{ "b1", LeafNode { { "four", 4 }, { "five", 5 }, { "six", 6 } } },
{ "b2", LeafNode { { "seven", 7 }, { "eight", 8 }, { "nine", 9 } } },
}
},
{ "c", LeafNode {} },
};
}
提示
为什么要区分内部/叶子节点?在我看来叶节点只是具有值的节点而不是子节点:
Live On Coliru
#include <boost/variant.hpp>
#include <unordered_map>
struct Data {
int _i;
Data(int i) : _i(i) {}
}; // just for illustration
using Tree = boost::make_recursive_variant<
Data,
std::unordered_map<std::string, boost::recursive_variant_>
>::type;
using Node = std::unordered_map<std::string, Tree>;
int main() {
Tree tree = Node {
{ "a", Node { { "one", 1 }, { "two", 2 }, { "three",3 } } },
{ "b", Node {
{ "b1", Node { { "four", 4 }, { "five", 5 }, { "six", 6 } } },
{ "b2", Node { { "seven", 7 }, { "eight", 8 }, { "nine", 9 } } },
}
},
{ "c", Node {} },
};
}
没有 Make-Recursive-Variant
您可以通过判断良好的前锋声明:
Live On Coliru
#include <boost/variant.hpp>
#include <unordered_map>
struct Data {
int _i;
Data(int i) : _i(i) {}
}; // just for illustration
struct Node;
using Tree = boost::variant<Data, boost::recursive_wrapper<Node> >;
struct Node : std::unordered_map<std::string, Tree> {
using base = std::unordered_map<std::string, Tree>;
using base::base; // inherit constructor
};
int main() {
Tree tree = Node {
{ "a", Node { { "one", 1 }, { "two", 2 }, { "three",3 } } },
{ "b", Node {
{ "b1", Node { { "four", 4 }, { "five", 5 }, { "six", 6 } } },
{ "b2", Node { { "seven", 7 }, { "eight", 8 }, { "nine", 9 } } },
}
},
{ "c", Node {} },
};
}
更优雅+更高效
如果您使用可以在映射类型仍然不完整时实例化的unordered_map,则根本不需要recursive_wrapper 的性能影响。
在这个过程中,我们可以让构造函数更加智能,树的构造更加简洁:
Live On Coliru
#include <boost/variant.hpp>
#include <boost/unordered_map.hpp>
struct Data {
int _i;
Data(int i = 0) : _i(i) {}
}; // just for illustration
struct Node : boost::variant<Data, boost::unordered_map<std::string, Node> > {
using Map = boost::unordered_map<std::string, Node>;
using Base = boost::variant<Data, Map>;
using Base::variant;
using Base::operator=;
Node(std::initializer_list<Map::value_type> init) : Base(Map(init)) {}
};
int main() {
auto tree = Node {
{ "a", { { "one", 1 }, { "two", 2 }, { "three", 3 } } },
{ "b", {
{ "b1", { { "four", 4 }, { "five", 5 }, { "six", 6 } } },
{ "b2", { { "seven", 7 }, { "eight", 8 }, { "nine", 9 } } },
}
},
{ "c", {} },
};
}
¹(我认为 c++17 将其添加到标准库规范中)