Voici quelques exemples (écrites de la mémoire):
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"));
Puis lire, il y a deux façons. L'un utilise boost :: get, l'autre utilise un visiteur. Le visiteur est généralement un peu plus robuste, mais si c'est un cas simple, boost :: get peut bien fonctionner.
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
Puisque vous itérez probablement, un visiteur fonctionnera probablement mieux. Vous créez un foncteur qui a des surcharges pour chaque type dans votre variante, et utilisez boost::apply_visitor
. Par exemple:
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);
}
Qu'avez-vous essayé jusqu'à présent? exemple de code – DimChtz
Si je suis correct 'boost :: variant, vector > v;' définit un vecteur 'v' avec des entrées int et string. Mais je ne sais pas comment le remplir. –
Sid
@DimChtz, j'ai aussi regardé le boost [tutoriel] (http://www.boost.org/doc/libs/1_55_0/doc/html/variant/tutorial.html) – Sid