The code below uses a boost variant of an std::map which contains int/MyVariant pairs. I am able to initialize my map correctly where the first element contains the 33/A pair and the second contains 44/B pair. A and B each have a function that I would like to be able to call after retrieving respectively their initialized map element:
#include "stdafx.h"
#include "boost/variant/variant.hpp"
#include "boost/variant/get.hpp"
#include "boost/variant/apply_visitor.hpp"
#include <map>
struct A { void Fa() {} };
struct B { void Fb() {} };
typedef boost::variant< A, B > MyVariants;
typedef std::map< const int, MyVariants > MyVariantsMap;
typedef std::pair< const int, MyVariants > MyVariantsMapPair;
struct H
{
H( std::initializer_list< MyVariantsMapPair > initialize_list ) : myVariantsMap( initialize_list ) {}
MyVariantsMap myVariantsMap;
};
int main()
{
H h { { 33, A {} }, { 44, B { } } };
auto myAVariant = h.myVariantsMap[ 33 ];
auto myBVariant = h.myVariantsMap[ 44 ];
A a;
a.Fa(); // ok
// but how do I call Fa() using myAVariant?
//myAVariant.Fa(); // not the right syntax
return 0;
}
What would be the correct syntax for doing that?
The boost::variant way to do this is using a visitor:
live example