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.Variant遍歷有界類型的序列
我能夠用升壓做到這一點::得到,但語法真的是很麻煩:
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;
}
EDIT 1
甲hackish的解決方案是:
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();
}
};
所以要通過對象和用於依賴於如果所述變體保持的A或B中的每個元件呼叫任一函數X或Y來迭代? – GManNickG 2010-06-20 05:21:56
是的,非常多:) – anno 2010-06-20 05:35:20