İşte (bellekten yazılmış) bazı örnekler:
typedef boost::variant<
std::string,
int
> StringOrInt; // using a typedef is just for convenience
StringOrInt myVariant;
myVariant = std::string("hello"); // both of these work
myVariant = 5;
std::vector<StringOrInt> myvec;
myvec.push_back(5);
myvec.push_back(std::string("hello"));
Sonra okumak için, iki yol vardır. Biri boost :: get, diğeri ziyaretçi kullanıyor. Ziyaretçi genellikle biraz daha sağlamdır, ancak basit bir durumsa, destek :: get iyi çalışabilir.
std::string& mystr = boost::get<std::string>(myvec[0]); // this will throw if the type you requested isn't what's stored
std::string* mystr = boost::get<std::string*>(myvec[0]); // pointer version doesn't throw
Muhtemelen yinelenen bir ziyaretçiden, muhtemelen bir ziyaretçi daha iyi çalışacaktır. Varyantınızdaki her tür için aşırı yüke sahip bir functor oluşturursunuz ve boost::apply_visitor
'u kullanın. Örneğin:
struct MyVisitor {
void operator()(const std::string& arg) const {
std::cout << "It was a string";
}
void operator()(int arg) const {
std::cout << "It was an int";
}
};
MyVisitor myVisitor;
for (auto& val : myvec) {
boost::apply_visitor(myVisitor, val);
}
Şimdiye kadar ne denediniz? örnek kod – DimChtz
Eğer 'boost :: variant, vektör > v;' doğruysa, int ve dize girişleriyle bir vektörü tanımlar. Ama onu nasıl dolduracağım konusunda emin değilim. –
Sid
@DimChtz, ayrıca [http://www.boost.org/doc/libs/1_55_0/doc/html/variant/tutorial.html) – Sid