我有一个 static_string 模板
template <std::size_t N>
struct static_string {
std::array<char, N + 1> elements_;
constexpr static_string() noexcept : elements_{} {}
constexpr static_string(const char (&data)[N + 1]) noexcept {
for (size_t i = 0; i < N + 1; i++) {
elements_[i] = data[i];
}
}
};
template <std::size_t N>
static_string(const char (&)[N]) -> static_string<N - 1>;
使用时效果很好
constexpr static_string str1("this is a str");
我想从 constexpr std::string_view 构造,所以我添加:
constexpr static_string(std::string_view sv) noexcept {
for (size_t i = 0; i < N; ++i) {
elements_[i] = sv[i];
}
}
那么如果我使用
constexpr std::string_view sv = "this is a str";
constexpr static_string<sv.size()> str2(sv);
编译器输出
<source>: In function 'int main()':
<source>:33:47: error: 'static_string<13>{std::array<char, 14>{std::__array_traits<char, 14>::_Type{'t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r'}}}' is not a constant expression
33 | constexpr static_string<sv.size()> str2(sv);
| ^
<source>:33:47: error: 'static_string<13>(sv)' is not a constant expression because it refers to an incompletely initialized variable
Compiler returned: 1
那么为什么这个表达式没有计算为常量,是否可以从 constexpr std::string_view 构造?谢谢,请参阅https://www.godbolt.org/z/6TToEPnch