作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
可以将 char 类型的值模板参数包解压为(编译时)字符串。如何将 string_view
获取到该字符串中?
我想做的事情:
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
有没有办法在 main
函数中获取行为?
最佳答案
它无法像 constexpr 一样工作,因为 s
数组位于堆栈上,所以它的地址在编译时是未知的。要修复,您可以将 s
声明为 static
。
关于c++ - 将参数包解压到字符串 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47126667/
我是一名优秀的程序员,十分优秀!