如何初始化 std::array<char, N>带有省略尾随 '\0' 的字符串文字 [英] How to initialize a std::array&lt;char, N&gt; with a string literal omitting the trailing &#39;\0&#39;

查看:28
本文介绍了如何初始化 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<char, N>带有省略尾随 '\0' 的字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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