我一直在開發一個變得非常大的庫,現在我添加了一些使用C++ 0x功能的基於模板的部分。所以我試着編譯我的庫(在當前標準下完全沒有警告地編譯),使用gcc版本4.4.5(在Linux上)標記-std=c++0x
。現在,我收到了大量有關將「臨時」變量轉換爲非常量引用的錯誤消息。問題是,他們不是暫時的!無效轉換爲C++中的非const引用0x ... std :: pair中的錯誤?
這裏是一個小的代碼塊重現錯誤:
#include <iostream>
#include <map>
struct scanner {
scanner& operator &(std::pair<std::string, int&> i) {
std::cout << "Enter value for " << i.first << ": ";
std::cin >> i.second;
return *this;
};
};
struct vect {
int q[3];
void fill(scanner& aScan) {
aScan & std::pair<std::string, int&>("q0",q[0])
& std::pair<std::string, int&>("q1",q[1])
& std::pair<std::string, int&>("q2",q[2]);
};
};
int main() {
vect v;
scanner s;
v.fill(s);
return 0;
};
如果您編譯此與現行標準(沒有的C++ 0x標誌),它會編譯和運行符合預期。但是,如果您有-std=c++0x
編譯它,它會拋出下面的錯誤在編譯時:
/usr/include/c++/4.4/bits/stl_pair.h:94: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
我真的不知道這一點。我已經瀏覽過網頁,但是沒有一個似乎有這個問題。它是std :: pair中的錯誤嗎?我真的很想知道問題所在。感謝您提供的任何見解。 PS:不要抱怨上述代碼的「質量」或「愚蠢」,它不是真正的代碼..只是一個顯示錯誤的例子。
你可以改變`運算符&`接受對其參數的const引用嗎?現在你正在傳遞價值,這需要製作一份副本,這是失敗的。 – 2011-02-01 16:53:25