Item 43 访问模板化基类中的名字

本文探讨了C++中模板特化的概念,并通过一个具体的应用案例解释了如何解决因模板特化导致的编译器疑惑问题。文章介绍了三种解决方法:使用this指针、using声明以及显式调用基类成员。

假设我们要写一个应用程序:
1> 它可以把消息传送到几个不同的公司去,且每个公司有自己的消息发送机制;
2> 消息既可以以加密方式也可以以明文的方式传送;
3> 有足够的信息在编译期间就可确定哪个消息将要发送给哪个公司
那么,可以用一个模板来解决问题。

class CompanyA // 公司A { public: ... void sendCleartext(const std::string& msg); void sendEncrypted(const std::string& msg); ... }; class CompanyB // 公司B { public: ... void sendCleartext(const std::string& msg); void sendEncrypted(const std::string& msg); ... }; ... // 其它的公司 class MsgInfo { ... }; // 这里保存着要发送的信息 template <typename Company> class MsgSender { public: ... // ctors, dtor, etc. 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: ... // ctors, dtor, etc. void sendClearMsg(const MsgInfo& info) { write "before sending" info to the log; sendClear(info); // 调用基类的函数。设计不错。但是编译会出错! write "after sending" info to the log; } ... };

为什么会出错?因为编译器报怨sendClear函数不存在。但是我们能看见该函数就在基类里,编译器为什么不去找呢?

看下面的类定义:

template<> // a total specialization of MsgSender; class MsgSender<CompanyZ> { // the same as the general template, except sendCleartext is omitted public: ... void sendSecret(const MsgInfo& info) { ... } };

因为CompanyZ只有密文传送,所以不能用template <typename Company> class MsgSender来实例化。只有用template<> class MsgSender<CompanyZ> 。
这种模板定义方法叫做:total template specialization。

正是因为有这种方法的存在,编译器才会对通用模板有疑问。有三种方法可以打消编译器的疑问:

>>> 使用this指针:

template<typename Company> class LoggingMsgSender: public MsgSender<Company> { public: ... void sendClearMsg(const MsgInfo& info) { write "before sending" info to the log; this->sendClear(info); // 给个this指针 write "after sending" info to the log; } ... };


>>> 使用using:

template<typename Company> class LoggingMsgSender: public MsgSender<Company> { public: using MsgSender<Company>::sendClear; // 告诉编译器,函数在基类里 ... void sendClearMsg(const MsgInfo& info) { ... sendClear(info); ... } ... };

>>> 显式地调用:

template<typename Company> class LoggingMsgSender: public MsgSender<Company> { public: ... void sendClearMsg(const MsgInfo& info) { ... MsgSender<Company>::sendClear(info); // 显式的调用 ... } ... };

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值