在理想情况下,我想以下列方式使用ClassVariant:
// store & retrieve int
map<string, ClassVariant> mapValues;
mapValues["int_fieldX"] = ClassVariant(20);
int fieldX = (mapValues["int_fieldX"])();
// Or int fieldX = (mapValues["int_fieldX"]);
但是,我只能实现以下代码,该代码需要检索语句来提供类型信息,如下所示:
int fieldB = (mapValuesTwo["int_fieldB"])(int(0));
如您所见,int(0)
作为类型信息提供。有没有办法可以消除这个限制。因此不需要类型信息。
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <boost/variant.hpp>
using namespace std;
typedef boost::variant<int, double, string> VarIntDoubleString;
class ClassVariant
{
public:
ClassVariant() : m_value(int(0)) {}
ClassVariant(VarIntDoubleString _val) : m_value(_val) {}
template<typename T>
T operator()(const T&) const
{
return boost::get<T>(m_value);
}
private:
VarIntDoubleString m_value;
};
int main(void)
{
map<string, ClassVariant> mapValuesTwo;
// store & retrieve int
mapValuesTwo["int_fieldB"] = ClassVariant(20);
int fieldB = (mapValuesTwo["int_fieldB"])(int(0));
cout << "fieldB: " << fieldB << endl;
// store & retrieve string
mapValuesTwo["int_fieldD"] = ClassVariant("Hello world");
string fieldD = (mapValuesTwo["int_fieldD"])(string(""));
cout << "fieldD: " << fieldD << endl;
}
// Output
fieldB: 20
fieldD: Hello world