2016-06-09 49 views
8

我有以下代碼:在返回類型的衝突從基類派生類中使用自動

struct A{}; 

struct Base { 
    virtual A& internal() = 0; 
}; 

struct Derives : public Base {  
    auto& internal() override { // <-- conflicting return type 
     return internal_; 
    } 

private: 
    A internal_; 
}; 

int main() { 
    Derives d; 
    auto& internal = d.internal(); 
} 

這編譯失敗(上coliru測試 - 用gcc)有衝突的返回類型 - 我的問題是,爲什麼編譯器不能推斷internal_(因此返回類型)是A?例如,在編譯的不同階段推導auto的類型是否與檢查虛擬覆蓋的類型相同?當然,如果您用正確的類型替換auto,則編譯 - 但除此之外。

(這裏是鐺錯誤,海灣合作委員會是有點類似)

main.cpp:8:11: error: return type of virtual function 'internal' is not covariant with the return type of the function it overrides ('auto &' is not derived from 'A &')

auto& internal() override { // <-- conflicting return type 
~~~~~^

main.cpp:4:16: note: overridden virtual function is here

virtual A& internal() = 0; 
     ~~^

1 error generated.

+1

想知道你爲什麼混合運行時多態性(虛擬函數)與優雅的編譯時間類的設計(模板)? – Ajay

+0

@BeyelerStudios,我看着這個問題,但我不相信它(雖然我可能是錯的..) – Nim

+2

在Visual Studio中,我得到:「錯誤C3542:導出::內部:虛擬成員函數沒有包含'auto'的返回類型 –

回答

14

[dcl.spec.auto]

A function declared with a return type that uses a placeholder type shall not be virtual ([class.virtual]).

internal()是一個虛函數,所以你不能使用auto

original proposal表示此推理:

It would be possible to allow return type deduction for virtual functions, but that would complicate both override checking and vtable layout, so it seems preferable to prohibit this.