What is the right c++ variant syntax for calling a

2019-06-05 14:04发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-06-05 14:28

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

查看更多
登录 后发表回答