条款43:学习处理模板化基类内的名称

发布于:2025-03-19 ⋅ 阅读:(19) ⋅ 点赞:(0)

前提认知:模板类继承模板类,是需要建立在假设的前提下的,如果没有这个”假设“,编译将会失败

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);        
    }
};


网站公告

今日签到

点亮在社区的每一天
去签到