gpt4 book ai didi

c++ - 类型特征以识别可以以二进制形式读/写的类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:41 26 4
gpt4 key购买 nike

是否有类型特征(或概念)来识别以下类型是安全的?

template <typename T>
std::enable_if_t<std::some_type_trait<T>::value> Write(std::ostream &os,const T &x)
{ os.write(reinterpret_cast<const char *>(&x),sizeof(T)); }

template <typename T>
std::enable_if_t<std::some_type_trait<T>::value> Read(std::istream &is,T &x)
{ is.read(reinterpret_cast<char *>(&x),sizeof(T)); }

我正在考虑包含 POD 的类,不包括指针(但不包括数组)。类似于 StandardLayoutType 但没有指针。我不想将对象限制为 TrivialTypeTriviallyCopyable

对不起,如果我不准确。我对数据表示知之甚少。

最佳答案

给定 s 的第一个st 参数,read方法:

Extracts characters and stores them into successive locations of the character array whose first element is pointed to by s

所以您真正的问题是:如果我通过向对象的地址写入一串字节来初始化对象,它是否有效?

这是Value Representation的概念.和 Trivially Copyable 的值表示类型是这样的:

Copying the bytes occupied by the object in the storage is sufficient to produce another object with the same value

因此你想确保你的对象是Trivially Copyable这不是一个标准的概念,但它可以简洁地定义为:

关于对象至少存在一个 Trivial 初始值设定项的断言的精神归结为 Trivially Copyable 类型的这些要求,它是非静态成员,并且它的任何基类:

  1. 给定的 Trivial Initializer 是或表现为相应的默认初始化器
  2. 没有虚方法
  3. 它没有 volatile 限定类型的成员

普通析构函数的要求而言:

  • The destructor is not user-provided (meaning, it is either implicitly declared, or explicitly defined as defaulted on its first declaration)
  • The destructor is not virtual (that is, the base class destructor is not virtual)
  • All direct base classes have trivial destructors
  • All non-static data members of class type (or array of class type) have trivial destructors

在完全定义了Trivially Copyable 类型后,“类型特征或概念”不可能确定是否在所有情况下都满足所有这些要求,例如:一个定义了一个普通初始化器的类型,其签名与默认初始化器匹配,可能普通可复制取决于在该初始化器主体中初始化该类型的代码;对于这样的类型,确定它是否Trivially Copyable 的唯一方法是人工检查初始化程序。但是,如果您愿意将要求收紧到 可检测到的程度,is_trivially_copyable将保证您的类型是Trivially Copyable

关于c++ - 类型特征以识别可以以二进制形式读/写的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40527028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com