2011-02-01 42 views
2

我一直在開發一個變得非常大的庫,現在我添加了一些使用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:不要抱怨上述代碼的「質量」或「愚蠢」,它不是真正的代碼..只是一個顯示錯誤的例子。

+0

你可以改變`運算符&`接受對其參數的const引用嗎?現在你正在傳遞價值,這需要製作一份副本,這是失敗的。 – 2011-02-01 16:53:25

回答

3

在gcc C++ 0x支持中有很多bug,但它還未完成,開發正在進行中。這對於gcc-4.4.5年齡的版本來說是雙倍的。如果你認真地在標準被批准之前開始C++ 0x開發,你需要使用編譯器和標準庫的最新版本。

3

它使用GCC 4.5.2編譯有和沒有-std=c++0x的罰款。

我猜GCC 4.4.5不支持C++ 0x那麼多得到這個工作。

4

您的代碼是無效的C++ 03,comeau給出(添加return語句運&後):

"stl_pair.h", line 44: error: qualifiers dropped in binding reference of 
      type "int &" to initializer of type "const int" 
    pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) {} 
                  ^
      detected during instantiation of "std::pair<_T1, _T2>::pair(const 
        _T1 &, const _T2 &) [with _T1=std::string, _T2=int &]" at 
        line 17 of "ComeauTest.c" 
... 

的問題是對內部的參考。如果我沒有記錯,這是一個gcc擴展,允許這樣做。 GCC確實與-std = GNU ++ 98,其是用於C++缺省值,但與-std接受它= C++ 98,GCC 4.4.3給出:

In file included from /usr/include/c++/4.4/bits/stl_algobase.h:66, 
       from /usr/include/c++/4.4/algorithm:61, 
       from PREAMBLE:7: 
/usr/include/c++/4.4/bits/stl_pair.h: In instantiation of ‘std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int&>’: 
<input>:5: instantiated from here 
/usr/include/c++/4.4/bits/stl_pair.h:83: error: forming reference to reference type ‘int&’ 
... 
2

除了在scanner& operator &(std::pair<std::string, int&> i)缺失return *this; ,你的代碼是有效的C++ 0x。

相關問題