4

可以将 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函数中的行为?

4

2 回答 2

3

它不能作为 constexpr 工作,因为s数组位于堆栈上,因此在编译时它的地址是未知的。要修复,您可以声明sstatic.

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

于 2017-11-05T21:30:08.850 回答
1

This code compiles in clang, though GCC still throws an (incorrect I think) error:

#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..., '\0' };
    static constexpr std::string_view str_view{&str[0]};
};

int main() {
    std::cout << stringify<'a','b','c'>::str_view;
    return 0;
}

Although it generates a warning about the "sub-object." (chars...) The other answer explains the reason this works.

于 2017-11-05T21:38:39.247 回答