【发布时间】:2019-04-29 13:47:54
【问题描述】:
我目前正在使用以字符串数据类型作为键和变量值的映射。我依靠 boost::variant 库来定义地图数据类型。我目前正在关注一些关于 boost::variant 的教程,用于从地图中提取值,而无需在迭代时指定我想要检索的确切数据类型值。 来源:https://theboostcpplibraries.com/boost.variant 我想要通用数据类型的最后一个示例,但不是打印我要返回的值。 以下内容似乎无法正常工作。
struct output : public boost::static_visitor<>
{
template <typename T>
T operator()(T t) const { return t }
};
我还实例化了一个映射,同时使用字符串数据类型作为键和 boost::variant 类型作为值填充它;稍后遍历地图并处理值。
std::map<std::string,boost::variant<int, double, long long, std::string>> _keyPairValue;
for(auto &x: _keyPairValue)
{
// appending a key pair value to a bson object which is part of mongo sdk
b << x.first << boost::apply_visitor(output{},x.second);
}
【问题讨论】:
-
请展开 "...似乎无法正常工作..." 所以我们知道问题出在哪里。
-
小记:从 C++17 开始,你应该也可以使用
std::variant代替。 -
你能提供一个minimal reproducible example吗?我觉得这个问题很难理解......