2017-09-22 39 views
0

我正在爲學習目的創建自己的字符串視圖類,並試圖使其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中實現的,如果:

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] 

如果swap不能和constexpr一起使用,爲什麼要使用constexpr?

+4

也許我誤解了這個問題,但你想交換兩個'constexpr'對象?按照定義,「constexpr」對象不能被修改,交換會執行。 –

+1

那麼爲什麼swap函數在'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

我現在用我自己的字符串視圖來測試它,它像你說的那樣完美地工作。我仍然覺得它有點不直觀,這是一種晦澀難懂的語言邊緣案例。謝謝 :) –