4

char 型の値テンプレート パラメーター パックを (コンパイル時の) 文字列にアンパックできます。その文字列にa をどのように取得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

1

このコードは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..., '\0' };
    static constexpr std::string_view str_view{&str[0]};
};

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

「サブオブジェクト」に関する警告が生成されますが。(文字...) 他の答えは、これが機能する理由を説明しています。

于 2017-11-05T21:38:39.247 に答える