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),我得到:
Run Code Online (Sandbox Code Playgroud)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);
}
Run Code Online (Sandbox Code Playgroud)