提升::访客多次使用相同的数据类型
Boost::visitor same data types several times
我尝试从协议实现数据结构。为了确保有效负载类型适合包含的数据,我有一个访问者函数来获取类型。在所有其他数据结构中,变体中使用了不同的类型,期望在有效载荷中
。enum class PayloadType : uint8_t {
Unsecured = 0,
Signed = 1,
Encrypted = 2,
Signed_External = 3,
Signed_And_Encrypted = 4
};
typedef ByteBuffer Unsecured;
typedef ByteBuffer Signed;
typedef ByteBuffer Encrypted;
typedef ByteBuffer SignedExternal;
typedef ByteBuffer SignedAndEncrypted;
typedef boost::variant<Unsecured, Signed, Encrypted, SignedExternal, SignedAndEncrypted> Payload;
现在的问题是,访问者中的每个类型都是相同的(例如,Signed 是 ab ByteBuffer,就像 Encrypted 是 ByteBuffer(。
PayloadType get_type(const Payload& payload) {
struct PayloadVisitor : public boost::static_visitor <> {
void operator()(const Unsecured& unsecured){
mtype = PayloadType::Unsecured;
}
void operator()(const Signed& sign){
mtype = PayloadType::Signed;
}
void operator()(const Encrypted& encrypted){
mtype = PayloadType::Encrypted;
}
void operator()(const SignedExternal& external){
mtype = PayloadType::Signed_External;
}
void operator()(const SignedAndEncrypted& sign){
mtype = PayloadType::Signed_And_Encrypted;
}
PayloadType mtype;
};
PayloadVisitor visit;
boost::apply_visitor(visit, payload);
return visit.mtype;
}
有没有办法使不同的类型彼此区分?
我发现它可以工作,如果我将它们放入以下结构中:
struct SignedExternal {
ByteBuffer buf;
}
struct Signed {
ByteBuffer buf;
}
and so on..
但是,处理数据类型非常冗长。也许有一个简单的方法可以实现这一点?
这里的问题是你尝试将typedef
用于它不是的东西:它没有声明一个新类型。(我认为对于 c++11 来说,这可能已经改变了,因为它允许 typedef'ed 模板(。如果有人能在标准中找到参考,我将不胜感激,但现在,从 cppreference.com:
typedef-names 是现有类型的别名,而不是新类型的声明。
你根本无法通过执行 typedef 来获得新类型。也许继承可能会帮助你,给你"真正的"新类型,但我不知道这在你的整个应用程序中是否是一个好主意。可能是 - 你的问题与多态性的想法非常吻合。
通常,c++ 是静态类型的,因此使用对象的类型作为信息的一部分的想法可能不是最好的。通常,您可能只希望缓冲区类具有引用enum
的字段"类型",并根据该字段的值进行操作。但那只是穷人的遗产。如果你想拥有可怜的C人的继承,也做同样的事情,但保存一个"做正确的事情"的函数指针和你的缓冲区。
您可以使用强大的 typedef
BOOST_STRONG_TYPEDEF(SignedExternal, ByteBuffer);
我记得其中有两个,一个在Bosot Utility中,一个在Boost Serialization中。
两者之一具有更多功能(例如提升一些运算符,例如我记得的比较/相等(。
- 防止主数据类型C++的隐式转换
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在C++中打印指向不同基元数据类型的指针的内存地址
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何计算数据类型的范围,例如int
- C++中数据类型修饰符的顺序
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 特定数据类型的模板类
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何获取C++字符数据类型的地址
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 构造智能点数据类型以及普通数据类型的通用方法
- 如何使映射键具有两种不同的数据类型?
- 数据类型"struct seq<0, 1, 2>{}"含义是什么?
- 如何在不破坏现有应用程序的情况下更改 API 中 stl 容器的数据类型?
- 具有不同返回类型的变体访客
- 提升::访客多次使用相同的数据类型