2017-09-22 6 views
0

私は自分のString Viewクラスを学習目的で作っています。私はそれを100%constexprにしようとしています。どのようにしてconstexprのスワップ機能を作成できますか?

これをテストするために、私はハッシュ値を返すメンバ関数を持っています。 switch文で文字列ビューを作成し、同じメンバ関数を呼び出します。渡すと、そのメンバ関数は目的をフルフィルにしています。

私はVisual Studio 2017の最新のアップデートstd::string_viewと私の実装を/読んで/比較していますが、swapconstexprとマークされていますが、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になるのですか?

+4

おそらく、私は質問を誤解していますが、2 'constexpr'オブジェクトを交換しようとしていますか?定義による 'constexpr'オブジェクトは変更できません。 –

+1

次に、スワップ関数は 'std :: string_view'にconstexprとしてマークされていますか? 'cppreference.com'の' std :: basic_string_view :: swap'の署名は 'constexpr void swap(basic_string_view&v)noexcept'です。なぜそれが 'constexpr'なのか知りたいです。 –

+1

それは興味深いです。おそらくあなたは*その質問に投稿する必要があります。 –

答えて

1

swapは、例えば、constexpr関数で呼び出すことを許可するconstexprをマークされている:

constexpr int foo() 
{ 
    int a = 42; 
    int b = 51; 

    swap(a, b); // Here swap should be constexpr, else you have error similar to: 
       // error: call to non-constexpr function 'void swap(T&, T&) [with T = int]' 
    return b; 
} 

Demo

+0

私は今自分の文字列ビューの実装でそれをテストし、あなたが言ったように完全に機能しました。私はまだそれが直感的ではない、言語のあいまいなケースであると考えています。ありがとう:) –

関連する問題