如何初始化std :: array< char,N>带有字符串文字的字符,省略了结尾的"\ 0" [英] How to initialize a std::array<char, N> with a string literal omitting the trailing '\0'

查看:304
本文介绍了如何初始化std :: array< char,N>带有字符串文字的字符,省略了结尾的"\ 0"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file structure where fixed length strings have no trailing zero. How to initialize fields as std::array without trailing zero:

#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)

推荐答案

创建辅助函数

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>());
}

然后

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

演示

这篇关于如何初始化std :: array&lt; char,N&gt;带有字符串文字的字符,省略了结尾的"\ 0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆