用于调用设置为特定变体的成员函数的正确 c++ 变体语法是什么

What is the right c++ variant syntax for calling a member function set to a particular variant?

本文关键字:c++ 语法 是什么 函数 成员 设置 用于 调用      更新时间:2023-10-16

下面的代码使用了包含int/MyVariant 对的 std::map 的 boost 变体。我能够正确初始化我的地图,其中第一个元素包含 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;
}

现场示例