2

我無法覆蓋使用模板參數包擴展指定的基類的虛擬方法 - 重寫方法將顯示實際相關類型。下面是一個MCVE:無法覆蓋使用模板參數包擴展聲明的虛擬方法

#include <iostream> 
template <typename... Ts> 
class A { virtual void foo(Ts&&...); }; 

class B : public A<int, unsigned> { 
    void foo(int x, unsigned y) override { std::cout << "here"; } 
}; 

int main() { 
    B b; 
} 

編譯此(與標準設置爲C++ 11或C++ 14),我得到:

a.cpp:9:7: error: ‘void B::foo(int, unsigned int)’ marked override, but does not override 
    void foo(int x, unsigned y) override { 
    ^
+4

看在基類的函數的簽名。 – Columbo

回答

7

基類的函數簽名是void foo(Ts&&...);

派生類的函數簽名是void foo(int x, unsigned y)

看到兩者有什麼不同嗎?區別是&&。爲了匹配基類的函數簽名,您需要派生類使用void foo(int&& x, unsigned&& y)

Demo:仔細

#include <iostream> 

template <typename... Ts> 
struct A { virtual void foo(Ts&&...) {} }; 

struct B : A<int, unsigned> { 
    void foo(int&& x, unsigned&& y) override { std::cout << "here"; } 
}; 

int main() { 
    B b; 
    b.foo(1, 2u); 
} 
+0

我在哪裏報告叮噹中的錯誤呢?另外,我的例子真的很模糊嗎? – einpoklum

+0

你是什麼版本的叮噹,你的代碼在3.7上正常工作:http://coliru.stacked-crooked.com/a/5695318de3b879c9而對於你的例子,我認爲你犯了一個常見的錯誤,模板T &&是一個通用的只有在模板參數與模板函數有直接關係的情況下。這裏,Ts && ...僅匹配右值引用。 – galop1n

+2

當然,它不鏈接,'A :: foo();'的定義在哪裏? – Barry