Effective C++(处理模板化基类内的名称)


author:

  • luixiao1223
    title: 处理模板化基类内的名称

例子代码

class CompanyA {
public:
    ...
void sendCleartext(const std::string& msg);
    void sendEncrypted(const std::string& msg);
    ...
};
class CompanyB {
public:
    ...
void sendCleartext(const std::string& msg);
    void sendEncrypted(const std::string& msg);
    ...
};

class MsgInfo { ... };
template<typename Company>
class MsgSender {
public:
    ...
void sendClear(const MsgInfo& info)
    {
        std::string msg;
        create msg from info;
    }
    Company c;
    c.sendCleartext(msg);
    void sendSecret(const MsgInfo& info)
    { ... }
};

问题:

template<typename Company>
class LoggingMsgSender: public MsgSender<Company> {
public:
    void sendClearMsg(const MsgInfo& info)
    {
        write "before sending" info to the log;
        sendClear(info); //无法通过编译
        write "after sending" info to the log;
    }
    ...
};

一个特化的版本

class CompanyZ {
public:
    ...
void sendEncrypted(const std::string& msg);
    ...
};


template<> //全特化
class MsgSender<CompanyZ> {
public:
    ...
void sendSecret(const MsgInfo& info)
    { ... }
};

编译器会抱怨sendClear不存在。原因是,base
class可能被特化,而特化的版本可能并不提供和一般性template相同的接口。因此编译器拒绝在继承而来的名称中找sendClear。

解决方案

1

template<typename Company>
class LoggingMsgSender: public MsgSender<Company> {
public:
    ...
void sendClearMsg(const MsgInfo& info)
    {
        write "before sending" info to the log;
        this->sendClear(info); //OK, 编程人员承诺一定有sendClear
        write "after sending" info to the log;
    }
    ...
};

2

template<typename Company>
class LoggingMsgSender: public MsgSender<Company> {
public:
    using MsgSender<Company>::sendClear; // 也是告诉编译器有sendClear

    void sendClearMsg(const MsgInfo& info)
    {
        ...;
        sendClear(info);
        ...;
    }
    ...
};

3 最不好的一个

template<typename Company>
class LoggingMsgSender: public MsgSender<Company> {
public:
    ...
void sendClearMsg(const MsgInfo& info)
    {
        ...;
        MsgSender<Company>::sendClear(info);
        ...;
    }
};

这种调用方法,可能屏蔽掉virtual函数的动态绑定。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值