当前位置: 首页 > news >正文

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

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

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

相关文章:

  • 提示deepseek生成完整的json用于对接外部API
  • 【Film】MovieAgent:自动化电影生成通过多智能体CoT规划
  • Linux上的`i2c-tools`工具集的详细介绍;并利用它操作IMX6ULL的I2C控制器进而控制芯片AP3216C读取光照值和距离值
  • 深度学习框架PyTorch——从入门到精通(1)下载与安装
  • flutter 专题 一百零三
  • MySQL如何存储表情符号?
  • LeetCode 第14~16题
  • 【gopher的java学习笔记】如何知道java应用启动过程中加载了哪些class
  • 【2025 最新 Cursor AI 教程 06】Cursor AI 与其他 AI 编码助手的比较
  • vue render函数开发高阶组件(HOC)
  • 卷积神经网络 - 卷积的变种、数学性质
  • 【多线程-第四天-SDWebImage介绍-复习前一天的内容 Objective-C语言】
  • 前端使用 crypto-js库AES加解密
  • 2024 年河南省职业院校 技能大赛高职组 “大数据分析与应用” 赛项任务书(一)
  • C语言中,#define和typedef 定义int* 一个容易混淆的点
  • 2025最新!人工智能领域大模型学习路径、大模型使用、AI工作流学习路径
  • 前端小食堂 | Day17 - 前端安全の金钟罩
  • 【深度学习量化交易16】触发机制设置——基于miniQMT的量化交易回测系统开发实记
  • 深度剖析Java开发中的双写一致性问题:原理、挑战与实战解决方案
  • 【如何在OpenWebUI中使用FLUX绘画:基于硅基流动免费API的完整指南】
  • 首映|《星际宝贝史迪奇》真人电影,不变的“欧哈纳”
  • 定制基因编辑疗法治愈罕见遗传病患儿
  • 涉案资金超2亿元 “健康投资”骗局,专挑老年人下手
  • 商务部:中方将适时发布中美经贸磋商相关消息
  • 泰山、华海、中路等山东险企综合成本率均超100%,承保业务均亏损
  • 苏轼“胡为适南海”?