gpt4 book ai didi

c++ - 将参数包解压到字符串 View 中

转载 作者:太空狗 更新时间:2023-10-29 21:12:32 24 4
gpt4 key购买 nike

可以将 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

Check this solution in online compiler

关于c++ - 将参数包解压到字符串 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47126667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com