2011-12-30 32 views
5

這個程序不使用clang++ test.cpp -std=c++0x編譯時:編譯錯誤調用重載函數的隱式轉換對象的舉動

class A 
{ 
public: 
    A() {} 
    A(const A&) {} 
    A(A&&) {} 
    A& operator = (const A&) { return *this; } 
    A& operator = (A&&) { return *this; } 
}; 

class B 
{ 
    A m_a; 
public: 
    operator const A &() const 
    { 
     return m_a; 
    } 
}; 

int main(int, char**) 
{ 
    A a; 
    B b; 
    a = b; // compile error 
} 

編譯錯誤:

Apple clang version 3.0 (tags/Apple/clang-211.10.1) (based on LLVM 3.0svn) 

test.cpp:25:9: error: no viable conversion from 'B' to 'A' 
    a = b; 
     ^
test.cpp:5:5: note: candidate constructor not viable: no known conversion from 'B' to 
     'const A &' for 1st argument 
    A(const A&) {} 
    ^
test.cpp:6:5: note: candidate constructor not viable: no known conversion from 'B' to 'A &&' 
     for 1st argument 
    A(A&&) {} 
    ^
test.cpp:15:5: note: candidate function 
    operator const A &() const 
    ^
test.cpp:8:23: note: passing argument to parameter here 
    A& operator = (A&&) { return *this; } 
        ^

爲什麼它不能編譯?爲什麼編譯器比A::operator = (const A&)更喜歡A::operator = (A&&)

另外,爲什麼要編譯A a = b;A a; a = b;(上面的程序)和A a(b);都沒有?

+0

Clang的哪個版本? – ildjarn 2011-12-30 18:31:12

+3

FWIW,你的代碼按原樣編譯爲'clang version 3.0(tags/RELEASE_30/final) Target:x86_64-pc-linux-gnu 線程模型:posix'和GCC 4.5.3或4.6.2(但我有不知道這是否正常) – Mat 2011-12-30 18:52:30

+0

看起來像叮噹蟲。 – 2011-12-31 17:42:38

回答

4

我不確定這是什麼錯誤,但是您正在測試的Clang版本相當陳舊,特別是在C++ 11功能方面。你可能想至少使用3.0 release of Clang,它正確接受這個AFAIK。我使用Clang SVN主幹的最新版本對它進行了測試,並且它運行良好。

鑑於Clang的C++ 11支持仍處於非常活躍的發展階段,如果3.0版本中還存在錯誤,請不要感到驚訝。直接從SVN中繼直接構建您可能會獲得更多成功。有指令here檢查從顛覆代碼和建立一套新的Clang二進制文件。

相關問題