用于保存 std::byte 的 C++ 类

fla*_*iu2 3 c++ c++17

有没有保存到文件std::bytes 中的 C++ 类?我已经使用了std::ofstream,但是需要强制转换才能执行它:

std::byte bt{ 1 };
std::ofstream ofs{};
ofs.write(reinterpret_cast<const char*>(bt), 1);
Run Code Online (Sandbox Code Playgroud)

你看:reinterpret_cast<const char*>?是否有其他std::byte无需任何强制转换即可保存的 C++ 类?

Ted*_*gmo 7

如果你不喜欢这个演员阵容,你可以自己制作ofstream

#include <array>
#include <cstddef>
#include <fstream>

using ofbytestream = std::basic_ofstream<std::byte>;

int main() {
    std::array<std::byte, 4> bytes{};
    ofbytestream ofs("bytes", std::ios_base::binary);
    ofs.write(bytes.data(), bytes.size()); // write 4 bytes without cast
}
Run Code Online (Sandbox Code Playgroud)

请注意,这与std::ofstream和 的std::wofstream定义方式非常相似。在本例中,第二个模板参数Traits默认为std::char_traits<std::byte>


上面的代码适用于 g++、clang++、MSVC 和 icx,这意味着您可能不需要做更多的事情 - 但是,我在标准中找不到任何需要实现来支持它的内容。如果您使用的实现不起作用则必须实现std::char_traits专门化。这是大纲,您需要填写static特征中函数的实现:

namespace std {
template <>
struct char_traits<byte> {
    using char_type = byte;
    using int_type = int;
    using off_type = streamoff;
    using pos_type = streampos;
    using state_type = mbstate_t;

    static constexpr void assign(char_type& c1, const char_type& c2) noexcept;
    static constexpr char_type* assign(char_type* ptr, std::size_t count,
                                       char_type c2);

    static constexpr bool eq(char_type a, char_type b) noexcept;
    static constexpr bool lt(char_type a, char_type b) noexcept;
    static constexpr char_type* move(char_type* dest, const char_type* src,
                                     std::size_t count);
    static constexpr char_type* copy(char_type* dest, const char_type* src,
                                     std::size_t count);
    static constexpr int compare(const char_type* s1, const char_type* s2,
                                 std::size_t count);
    static constexpr std::size_t length(const char_type* s);
    static constexpr const char_type* find(const char_type* ptr,
                                           std::size_t count,
                                           const char_type& ch);
    static constexpr char_type to_char_type(int_type c) noexcept;
    static constexpr int_type to_int_type(char_type c) noexcept;
    static constexpr bool eq_int_type(int_type c1, int_type c2) noexcept;
    static constexpr int_type eof() noexcept;
    static constexpr int_type not_eof(int_type e) noexcept;
};
}  // namespace std
Run Code Online (Sandbox Code Playgroud)

请注意,除了标准库中的专业化std::char_traits之外,不需要满足指定要求CharTraits中的要求。