将参数包解压缩到字符串视图中 [英] Unpack parameter pack into string view

查看:82
本文介绍了将参数包解压缩到字符串视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将char类型的值模板参数包解压缩到(编译时)字符串中。
一个人如何在该字符串中获取 string_view

It is possible to unpack a value template parameter pack of type char into a (compile time) string. How does one acquire a string_view into that string?

我想做什么:

int main()
    {
    constexpr auto s = stringify<'a', 'b', 'c'>();
    constexpr std::string_view sv{ s.begin(), s.size() };
    return 0;
    }

尝试:

template<char ... chars>
constexpr auto stringify()
    {
    std::array<char, sizeof...(chars)> array = { chars... };
    return array;
    }

错误:

15 : <source>:15:30: error: constexpr variable 'sv' must be initialized by a constant expression
constexpr std::string_view sv{ s.begin(), s.size() };
                         ^~~~~~~~~~~~~~~~~~~~~~~~~
15 : <source>:15:30: note: pointer to subobject of 's' is not a constant expression

有没有办法获取<$中的行为c $ c> main 函数?

推荐答案

它不能用作constexpr,因为 s 数组位于堆栈上,因此在编译时不知道其地址。要解决此问题,您可以将 s 声明为 static

It fails to work as constexpr because s array is located on the stack so its address is not known at compile time. To fix you can declare s as static.

在在线编译器中检查此解决方案

这篇关于将参数包解压缩到字符串视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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