调用成员函数集到特定变量的正确c ++变体语法是什么?

时间:2016-07-08 19:54:14

标签: c++ stdmap boost-variant

下面的代码使用std :: map的boost变体,它包含int / MyVariant对。我可以正确初始化我的地图,其中第一个元素包含33 / A对,第二个元素包含44 / B对。 A和B每个都有一个函数,我希望能够分别检索它们的初始化地图元素后调用:

#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;
}

这样做的正确语法是什么?

1 个答案:

答案 0 :(得分:3)

boost :: variant的方法是使用访问者:

#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