如何从 constexpr std::string_view 构造 constexpr static_string

问题描述 投票:0回答:1

我有一个 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

c++ constexpr string-view constant-expression
1个回答
0
投票

编译器发出的错误消息具有误导性。

事实上,问题与输入

string_view
无关,而是与
elements_
未完全初始化有关,这在
constexpr
构造函数中是不允许的。

要解决此问题,只需添加缺少的空终止字符:

#include <array>
#include <iostream>
#include <string_view>

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];
        }
    }

    constexpr static_string(const std::string_view& sv) noexcept {
        for (size_t i = 0; i < N; ++i) {
            elements_[i] = sv[i];
        }
        elements_[N] = '\0';  // completing the initialization of the object
    }
};

template <std::size_t N>
static_string(const char (&)[N]) -> static_string<N - 1>;

int main() {
    constexpr std::string_view sv = "this is a str";
    constexpr static_string str1("this is a str");
    constexpr static_string<sv.size()> str2(sv);
}
© www.soinside.com 2019 - 2024. All rights reserved.