2

私は学習目的で独自の String View クラスを作成しており、それを 100% constexpr にしようとしています。

それをテストするために、ハッシュ値を返すメンバー関数があります。次に、switch ステートメントで文字列ビューを作成し、同じメンバー関数を呼び出します。成功した場合、そのメンバー関数はその目的を果たしています。

学ぶために、私は自分の実装を Visual Studio 2017 の最新の更新プログラムと使用/読み取り/比較していますが、としてマークされているにもかかわらず、Visual Studio でも g++ でも機能しないことstd::string_viewに気付きました。swapconstexpr

これは機能しないコードです。

constexpr Ali::String::View hello("hello");
constexpr Ali::String::View world("world");
// My implementation fails here!
hello.swap(world);
cout << hello << " " << world << endl;    

// Visual Studio implementation fails here!
// std::string_view with char const * is not constexpr because of the length
constexpr std::string_view hello("hello");
constexpr std::string_view world("world");
hello.swap(world);
cout << hello << " " << world << endl;

これは、if の Visual Studio 実装です。

constexpr void swap(basic_string_view& _Other) _NOEXCEPT
        {   // swap contents
        const basic_string_view _Tmp{_Other};   // note: std::swap is not constexpr
        _Other = *this;
        *this = _Tmp;
        }

これは私のクラスのもので、Visual Studio のものと似ています。

constexpr void swap(View & input) noexcept {
    View const data(input);
    input = *this;
    *this = data;
}

すべてのコンストラクターと代入は、constexpr としてマークされます。

Visual Studio と g++ の両方で同様のエラーが発生します。

// Visual Studio
error C2662: 'void Ali::String::View::swap(Ali::String::View &) noexcept': cannot convert 'this' pointer from 'const Ali::String::View' to 'Ali::String::View &'

// g++
error: passing 'const Ali::String::View' as 'this' argument discards qualifiers [-fpermissive]

スワップが constexpr で機能しない場合、なぜ constexpr を使用するのですか?

4

1 に答える 1