无法覆盖使用模板参数包扩展声明的虚方法

ein*_*ica 2 c++ virtual-functions variadic-functions variadic-templates c++11

我无法覆盖使用模板参数包扩展指定的基类的虚方法 - 而重写方法将显示实际的相关类型.这是一个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;
}
Run Code Online (Sandbox Code Playgroud)

编译它(标准设置为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 {
       ^
Run Code Online (Sandbox Code Playgroud)

Cor*_*lks 7

基类的函数签名是void foo(Ts&&...);.

派生类的函数签名是void foo(int x, unsigned y).

看到两者之间有什么不同?不同的是&&.为了匹配基类的函数签名,您需要使用派生类void foo(int&& x, unsigned&& y).

演示:

#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);
}
Run Code Online (Sandbox Code Playgroud)

  • @ galop1n这里没有编译器错误. (3认同)
  • 当然它没有链接,`A :: foo();`的定义在哪里? (2认同)