提升::访客多次使用相同的数据类型

Boost::visitor same data types several times

本文关键字:数据类型 访客 提升      更新时间:2023-10-16

我尝试从协议实现数据结构。为了确保有效负载类型适合包含的数据,我有一个访问者函数来获取类型。在所有其他数据结构中,变体中使用了不同的类型,期望在有效载荷中

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中。

两者之一具有更多功能(例如提升一些运算符,例如我记得的比较/相等(。