C++ 从包含变量数据类型的数据结构中检索值,而不指定返回类型
我目前正在使用一个以字符串数据类型作为键和变量值的映射。我依赖boost::variant库来定义映射数据类型。目前,我正在学习一些关于boost::variant的教程,用于从映射中提取值,而无需在遍历映射时指定要检索的确切数据类型值。 资料来源: 我想要像上一个通用数据类型示例一样的东西,但不是打印值,而是返回它们。 以下各项似乎无法正常工作C++ 从包含变量数据类型的数据结构中检索值,而不指定返回类型,c++,boost,C++,Boost,我目前正在使用一个以字符串数据类型作为键和变量值的映射。我依赖boost::variant库来定义映射数据类型。目前,我正在学习一些关于boost::variant的教程,用于从映射中提取值,而无需在遍历映射时指定要检索的确切数据类型值。 资料来源: 我想要像上一个通用数据类型示例一样的东西,但不是打印值,而是返回它们。 以下各项似乎无法正常工作 struct output : public boost::static_visitor<> { template <typen
struct output : public boost::static_visitor<>
{
template <typename T>
T operator()(T t) const { return t }
};
struct输出:public boost::static\u visitor
{
模板
T运算符()(T)常量{return T}
};
我还实例化了一个映射,同时使用字符串数据类型作为键和boost::variant type作为值填充它;然后遍历映射并处理值
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);
}
std::map\u keyPairValue;
用于(自动和x:_键对右值)
{
//将密钥对值附加到作为mongo sdk一部分的bson对象
B
我想要像上一个通用数据类型示例一样的东西,但不是打印值,而是返回它们
您可能希望有operator()
重载,例如:
struct process : public boost::static_visitor<>
{
void operator()(double d)
{
// process d ...
}
void operator()(char c)
{
// process c ...
}
void operator()(const string& s)
{
// process s ...
}
};
int main()
{
boost::variant<double, char, std::string> v;
v = 3.14;
boost::apply_visitor(process{}, v);
v = 'A';
boost::apply_visitor(process{}, v);
v = "Boost";
boost::apply_visitor(process{}, v);
}
struct进程:public boost::static\u visitor
{
void运算符()(双d)
{
//过程d。。。
}
void运算符()(字符c)
{
//过程c。。。
}
void运算符()(常量字符串(&s)
{
//过程s。。。
}
};
int main()
{
boost::变体v;
v=3.14;
boost::apply_visitor(进程{},v);
v='A';
boost::apply_visitor(进程{},v);
v=“Boost”;
boost::apply_visitor(进程{},v);
}
请详细说明“…似乎工作不正常…”,这样我们就知道问题所在。小提示:从C++17开始,您也应该能够使用。您能提供一个答案吗?我发现这个问题很难理解。。。