如何使用字符串文字初始化std :: array <char,N>,省略尾部'\ 0'

7 c++ arrays c++11

我有一个文件结构,其中固定长度字符串没有尾随零.如何将字段初始化为std :: array而不是尾随零:

#pragma pack(push, 1)
struct Data {
    // Compiles, but it has an undesired '\0':
    std::array<char, 6> undesired_number{"12345"};
    // Does not compile:
    std::array<char, 5> number{"12345"}; // stripping '\0'
};
#pragma pack(pop)
Run Code Online (Sandbox Code Playgroud)

Jar*_*d42 15

做一个帮手功能

template <std::size_t N, std::size_t ... Is>
constexpr std::array<char, N - 1>
to_array(const char (&a)[N], std::index_sequence<Is...>)
{
    return {{a[Is]...}};
}

template <std::size_t N>
constexpr std::array<char, N - 1> to_array(const char (&a)[N])
{
    return to_array(a, std::make_index_sequence<N - 1>());
}
Run Code Online (Sandbox Code Playgroud)

然后

struct Data {
    std::array<char, 5> number{to_array("12345")}; // stripping '\0'
};
Run Code Online (Sandbox Code Playgroud)

演示