覆盖使用模板参数包扩展声明的虚拟方法时遇到问题

Having trouble overriding a virtual method declared with template parameter pack expansion

本文关键字:声明 虚拟 方法 问题 遇到 扩展 参数 包扩展 覆盖      更新时间:2023-10-16

我在重写使用模板参数包扩展指定的基类的虚拟方法时遇到问题 - 而覆盖方法将显示实际的相关类型。这是一个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 {
       ^

基类的函数签名是 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);
}
相关文章: