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

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

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

最佳答案

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

关于c++ - 调用成员函数集到特定变体的正确c++变体语法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38274440/

10-11 06:27
查看更多