struct A
{
std::string get_string();
};
struct B
{
int value;
};
typedef boost::variant<A,B> var_types;
std::vector<var_types> v;
A a;
B b;
v.push_back(a);
v.push_back(b);
v の要素を繰り返し処理して a および b オブジェクトにアクセスするにはどうすればよいですか?
私はboost::getでそれを行うことができますが、構文は本当に面倒です.:
std::vector<var_types>:: it = v.begin();
while(it != v.end())
{
if(A* temp_object = boost::get<A>(&(*it)))
std::cout << temp_object->get_string();
++it;
}
訪問テクニックを使用しようとしましたが、あまりうまくいかず、コードが機能していません:
template<typename Type>
class get_object
: public boost::static_visitor<Type>
{
public:
Type operator()(Type & i) const
{
return i;
}
};
...
while(it != v.end())
{
A temp_object = boost::apply_visitor(get_object<A>(),*it);
++it;
}
編集1
ハックな解決策は次のとおりです。
class get_object
: public boost::static_visitor<A>
{
public:
A operator()(const A & i) const
{
return i;
}
A operator()(const B& i) const
{
return A();
}
};