问题
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?
What I want to do:
int main()
{
constexpr auto s = stringify<'a', 'b', 'c'>();
constexpr std::string_view sv{ s.begin(), s.size() };
return 0;
}
Try:
template<char ... chars>
constexpr auto stringify()
{
std::array<char, sizeof...(chars)> array = { chars... };
return array;
}
Error:
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
Is there a way to get a the behaviour in the main
function?
回答1:
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
.
Check this solution in online compiler
回答2:
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.
来源:https://stackoverflow.com/questions/47126667/unpack-parameter-pack-into-string-view