前提认知:模板类继承模板类,是需要建立在假设的前提下的,如果没有这个”假设“,编译将会失败
1.书上举例
2.完整代码举例
#include <iostream>
class MsgInfo { };
class BaseCompany
{
public:
BaseCompany(){}
~BaseCompany(){}
};
class BaseCompany1
{
public:
BaseCompany1(){}
~BaseCompany1(){}
};
template<typename Company>
class MsgSender
{
public:
void Clear(const MsgInfo& info) {}
};
template<>
class MsgSender<BaseCompany1>{};
template<typename Company>
class LoggingMsgSender : public MsgSender<Company> {
public:
void SendClearMsg(const MsgInfo& info) {
/* this->*/Clear(info);
}
};
int main()
{
LoggingMsgSender<BaseCompany> t;
return 0;
}
- 编译器报错
main.cpp: In member function 'void LoggingMsgSender<Company>::SendClearMsg(const MsgInfo&)':
main.cpp:35:20: error: there are no arguments to 'Clear' that depend on a template parameter, so a declaration of 'Clear' must be available [-fpermissive]
35 | /* this->*/Clear(info);
| ^~~~~
main.cpp:35:20: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)
3.三种解决方式,建立“假设”
- 使用this->clear(info),告诉编译器假设父类有这个函数
template<typename Company>
class LoggingMsgSender : public MsgSender<Company> {
public:
void SendClearMsg(const MsgInfo& info) {
this->Clear(info);
}
};
- 使用using
template<typename Company>
class LoggingMsgSender : public MsgSender<Company> {
using MsgSender<Company>::Clear;
public:
void SendClearMsg(const MsgInfo& info) {
Clear(info);
}
};
- 指定父类的函数
template<typename Company>
class LoggingMsgSender : public MsgSender<Company> {
public:
void SendClearMsg(const MsgInfo& info) {
MsgSender<Company>::Clear(info);
}
};