问题
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?
回答1:
The boost::variant way to do this is using a visitor:
#include <boost/variant/variant.hpp>
#include <map>
#include <iostream>
struct A { void Fa() {std::cout << "A" << std::endl;} };
struct B { void Fb() {std::cout << "B" << std::endl; } };
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;
};
class Visitor
: public boost::static_visitor<>
{
public:
void operator()(A& a) const
{
a.Fa();
}
void operator()(B& b) const
{
b.Fb();
}
};
int main()
{
H h { { 33, A {} }, { 44, B { } } };
auto myAVariant = h.myVariantsMap[ 33 ];
auto myBVariant = h.myVariantsMap[ 44 ];
boost::apply_visitor(Visitor(), myAVariant);
boost::apply_visitor(Visitor(), myBVariant);
return 0;
}
live example
来源:https://stackoverflow.com/questions/38274440/what-is-the-right-c-variant-syntax-for-calling-a-member-function-set-to-a-part