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的类,不包括指针(但不包括数组).像StandardLayoutTypes但没有指针的东西.我既不想将对象约束为TrivialType也不想将TriviallyCopyable约束.
对不起,如果我不准确.我对数据表示知之甚少.
解决方法
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
因此,您希望确保您的对象是平凡可复制的,这不是标准概念,但它可以简洁地定义为:
- Every 07003 or deleted
- Every 07004 or deleted
- Every 07005 or deleted
- Every 07006 or deleted
- At least one copy constructor,move constructor,copy assignment operator,or move assignment operator is non-deleted
- 07007
对于对象存在至少一个Trivial初始值设定项的断言的精神归结为Trivially Copyable类型的这些要求,它是非静态成员,以及它的任何基类:
>它被赋予Trivial Initializer,或者表现为相应的默认初始化器
>它没有虚拟方法
>它没有volatile限定类型的成员
至于Trivial析构函数的要求:
- 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类型意味着什么,“类型特征或概念”不可能确定是否在所有情况下都满足所有这些要求,例如:定义具有签名的Trivial Initializer的类型匹配默认初始化程序可能是也可能不是Trivially Copyable,取决于初始化该初始化程序主体中的类型的代码;对于这种类型,确定它是否可以简单复制的唯一方法是对初始化程序进行人工检查.但是,如果您愿意将要求收紧到可检测的要求,is_trivially_copyable
将保证您的类型可以轻易复制.