用于调用设置为特定变体的成员函数的正确 c++ 变体语法是什么
What is the right c++ variant syntax for calling a member function set to a particular variant?
下面的代码使用了包含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;
}
现场示例
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 单独定义模板化嵌套类方法的正确语法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 使用基类指针调用基类的值构造函数的语法是什么?
- 很好的语法来获取对向量/数组数据的大小引用?
- C++语法运算符功能?
- C++使用 rand 定义函数语法
- 什么文件可以修改 atom 的C++语法?
- 创建模板嵌套类实例的语法?
- C++语法差异:二维和一维数组(指针算术)
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么