将参数包解压缩到字符串视图中

Unpack parameter pack into string view

本文关键字:字符串 视图 解压缩 参数      更新时间:2023-10-16

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

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

这段代码在 clang 中编译,尽管 GCC 仍然抛出一个(我认为不正确的)错误:

#include <iostream>
#include <array>
#include <string_view>
template<char... chars>
struct stringify {
    // you can still just get a view with the size, but this way it's a valid c-string
    static constexpr std::array<char, sizeof...(chars) + 1> str = { chars..., '' };
    static constexpr std::string_view str_view{&str[0]};
};
int main() {
    std::cout << stringify<'a','b','c'>::str_view;
    return 0;
}

尽管它会生成有关"子对象"的警告。(字符...另一个答案解释了这样做的原因。