什么是正确的c ++变体语法调用成员函数设置为特定的变体? [英] What is the right c++ variant syntax for calling a member function set to a particular variant?

查看:250
本文介绍了什么是正确的c ++变体语法调用成员函数设置为特定的变体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

活动示例

这篇关于什么是正确的c ++变体语法调用成员函数设置为特定的变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆