截断在编译时的String [英] Truncate a String at Compile-Time

查看:162
本文介绍了截断在编译时的String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串与超出我的控制(例如一个的#define 的config.h 文件),我想初始化一个全球固定大小的字符数组它。如果字符串太长,我希望它被截断。

基本上,我想实现的是效果

 的#define SomeText则会Lorem存有
的#define LIMIT 8字符文本[LIMIT + 1];
的std ::函数strncpy(文字,SOMETEXT,LIMIT);
文[LIMIT] ='\\ 0';

只是因为我想我不能用这个code

文本是一个静态初始化 constexpr

我怎样才能做到这一点?


  

注意:我已经找到了解决这个问题,但由于对堆栈溢出搜索没有取得我一个满意的结果(类似的问题尽管很多有用的提示),我想分享我的解。如果你有一个更好的(更优雅)解决方案,请仍然表现出来。我将接受最优雅的答案在一个星期内。



解决方案

另一种方法来创建的std ::阵列

 详细的命名空间
{
    模板< typename的C,性病::为size_t N,性病::为size_t ...是>
    constexpr的std ::阵列< C,...的sizeof(IS)+ 1 GT;截断(常量C(&放大器; S)[N],的std :: index_sequence<是...>)
    {
        返回{(为< N S [是]:与的static_cast LT; C>(0))...的static_cast< C>(0)};
    }}模板<的std ::为size_t L,类型名称C,性病::为size_t N'GT;
constexpr的std ::阵列下; C,L + 1>截断(常量C(&放大器; S)[N])
{
    返回细节::截断(S,性病:: make_index_sequence< L> {});
}

演示

I have a string literal with a value that is out of my control (for example a #define in a config.h file) and I want to initialize a global fixed-size character array with it. If the string is too long, I want it to be truncated.

Basically, what I want to achieve is the effect of

#define SOMETEXT "lorem ipsum"
#define LIMIT 8

char text[LIMIT + 1];
std::strncpy(text, SOMETEXT, LIMIT);
text[LIMIT] = '\0';

except that I cannot use this code because I want text to be a statically initialized constexpr.

How can I do this?

Note: I have already found a solution to this problem but since a search on Stack Overflow did not yield me a satisfactory result (though many helpful hints for similar problems), I wanted to share my solution. If you have a better (more elegant) solution, please show it nevertheless. I will accept the most elegant answer in one week.

解决方案

An alternative to create the std::array:

namespace detail
{
    template <typename C, std::size_t N, std::size_t...Is>
    constexpr std::array<C, sizeof...(Is) + 1> truncate(const C(&s)[N], std::index_sequence<Is...>)
    {
        return {(Is < N ? s[Is] : static_cast<C>(0))..., static_cast<C>(0)};
    }

}

template <std::size_t L, typename C, std::size_t N>
constexpr std::array<C, L + 1> truncate(const C(&s)[N])
{
    return detail::truncate(s, std::make_index_sequence<L>{});
}

Demo

这篇关于截断在编译时的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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