C++子类重写模板父类的函数
因为项目上的框架已经搭建好,想子类重写模板类的函数,中途遇见一点问题,特此记录
#include <iostream>
#include <functional>
// 测试模板类里的函数是否可以被子类重写 是的,可以
template <typename MsgType>
class A{
public:
[[nodiscard]] virtual int get(std::function<void(const MsgType&)> callback){
std::cout<<"a MsgType";
// callback();
return 0;
}
};
template <typename TypeName>
class B:public TypeName{
public:
};
class C:public B< A<int> >{
public:
[[nodiscard]] int get(std::function<void(const int&)> callback) override{
std::cout<<"c msgType";
callback(100);
return 0;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
A<int>* c = new C();
c->get([](int msg){std::cout<<msg;});
return 0;
}
这个代码的输出是:
Hello, World!
c msgType100
如果std::function<void(const MsgType&)> 与 std::function<void(const int&)> 中参数的引用方式不一致,使用override会编译通不过