确定变体类型
identify variant type
本文关键字:类型 更新时间:2023-10-16
我通过在boost::variant
中识别特定类型并将其作为类对象中的成员函数参数传递来混淆以下问题。请考虑以下代码
typedef boost::variant<int, string, double> Variant;
class test{
void func1 (Variant V);
void func2 (string s);
void func3 ();
};
test::func1(Variant V){
// How can I identify the type of V inside the body of this function?
Or how can I call the apply_visitor inside this function.
/*
if(v.type() == string)
func2();
else if(v.type() == double)
funct3();
*/
}
int test::func2(){ cout << "func3" << endl;}
int test::func3(){ cout << "func4" << endl;}
...
int main ()
{
test t;
Variant V = 3;
t.func1(V);
V = "hello";
t.func1(V);
}
我想确定在类测试中实现访问类/结构(apply_visitor)。但是,我从访问者类中实现的重载运算符调用一个外部成员函数,即func3(字符串s)而陷入困境。
访问者模式重新化将使编译器为您执行类型检查。 您需要做的就是告诉编译器当string
在Variant
中时该怎么做:
(查看示例http://www.boost.org/doc/libs/1_35_0/doc/html/variant/tutorial.html)
struct my_dispatcher : public boost::static_visitor<> {
test* t;
my_dispatcher(test* t): t(t) {}
void operator()( string s ) { t.func3(s); }
void operator()( double d ) { t.func4(d); }
//... for each supported type
};
并使用boost::apply_visitor
选择正确的功能:
int main ()
{
test t;
my_dispatcher dispatcher(&t);
Variant V = 3;
boost::apply_visitor( dispatcher, v );
V = "hello";
boost::apply_visitor( dispatcher, v );
}
my_dispatcher(&t)
将创建您的static_visitor实现对象,该对象将由apply_visitor
魔法使用。
希望这就是你所期待的,因为你的问题不是很清楚。
注意:或者,您可以从static_visitor
派生test
。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型