我定义了以下类型的d
typedef boost::variant<string, double> flex_String_Double;
map<string, flex_String_Double> FDParam;
FDParam的形式如下:
{"setNumber", 3}
{"Money", 3.152}
{"Fight", "No"}
我想做的是(期望获得 6.152):
cout << FDParam["setNumber"] + FDParam["Money"] << endl;
但是,此命令不起作用,并给我以下错误:
Invalid operands to binary expression ('std::__1::map<std::__1::basic_string<char>, boost::variant<std::__1::basic_string<char>, double>, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, boost::variant<std::__1::basic_string<char>, double> > > >::mapped_type' (aka 'boost::variant<std::__1::basic_string<char>, double>') and 'double')
任何人都可以帮助我解决这个问题吗?
你必须
使用boost::get<T>
从变体中推断出你想要采取的类型......
#include <iostream>
#include <map>
#include <boost/variant.hpp>
typedef boost::variant<std::string, double> flex_String_Double;
std::map<std::string, flex_String_Double> FDParam;
int main()
{
FDParam["setNumber"] = 3;
FDParam["Money"] = 3.152;
FDParam["Fight"] = "No";
std::cout << boost::get<double>(FDParam["setNumber"]) +
boost::get<double>(FDParam["Money"]) << std::endl;
std::cout << "Can Fight? " << boost::get<std::string>(FDParam["Fight"]) << std::endl;
}
编辑:此外,如果您不考虑使用全局变量,此代码可以缩短得多...如果您希望任何其他函数访问/修改变量,请使用引用...
#include <iostream>
#include <map>
#include <boost/variant.hpp>
typedef boost::variant<std::string, double> flex_String_Double;
int main()
{
std::map<std::string, flex_String_Double> FDParam = {
{ "setNumber", 3 },
{ "Money", 3.152 },
{ "Fight", "No" },
};
std::cout << boost::get<double>(FDParam["setNumber"]) +
boost::get<double>(FDParam["Money"]) << std::endl;
std::cout << "Can Fight? " << boost::get<std::string>(FDParam["Fight"]) << std::endl;
}