私は自分のString Viewクラスを学習目的で作っています。私はそれを100%constexprにしようとしています。どのようにしてconstexprのスワップ機能を作成できますか?
これをテストするために、私はハッシュ値を返すメンバ関数を持っています。 switch文で文字列ビューを作成し、同じメンバ関数を呼び出します。渡すと、そのメンバ関数は目的をフルフィルにしています。
私はVisual Studio 2017の最新のアップデートstd::string_view
と私の実装を/読んで/比較していますが、swap
はconstexpr
とマークされていますが、Visual Studioでは、 g ++ではなく
これは動作しないコードの一部です:
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;
そして場合、これはのVisual Studioの実装です:この1つは私のクラスからであり、それは1に似てい
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になるのですか?
おそらく、私は質問を誤解していますが、2 'constexpr'オブジェクトを交換しようとしていますか?定義による 'constexpr'オブジェクトは変更できません。 –
次に、スワップ関数は 'std :: string_view'にconstexprとしてマークされていますか? 'cppreference.com'の' std :: basic_string_view :: swap'の署名は 'constexpr void swap(basic_string_view&v)noexcept'です。なぜそれが 'constexpr'なのか知りたいです。 –
それは興味深いです。おそらくあなたは*その質問に投稿する必要があります。 –