读书人

effective c++中条款43的有关问题

发布时间: 2012-09-25 09:55:59 作者: rapoo

effective c++中条款43的问题
书中内容如下:
我们需要一个程序,传送信息到不同的公司去。信息要不译成密码,要不就是未加工的文字。如果编译期间我们有足够信息来决定哪一个信息传至那一家公司,就可以采用基于template的解法:
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);
};
... //针对其他公司设计的classes
class MsgInfo{...}; //这个class用来保存信息,以备将来产生信息
template<typename Company>
class MsgSender{
public:
void sendClear(const MsgInfo& info)
{
std::string msg;
根据info产生信息;
Company c;
c.sendCleartext(msg);
}
void sendSecret(const MsgInfo& info)
{
...;//调用c.sendEncrypted,类似sendClear
}
};
这个做法行的通。但假设我们有时候想要在每次发送出信息的时候志记(log)某些信息。derived class可以轻易加上这样的行为,那似乎是个合情理的解法:
template<typename Company>
class LoggingMsgSender: public MsgSender<Company>{
public:
void sendClearMsg(const MsgInfo& info)
{
将传送前信息写至log;
sendClear(info);
}
};
sendClearMsg 避免遮掩“继承而得的名称”(条款33),避免重新定义一个继承而得的non-virtual函数(条款36)。但上述代码无法通过编译,编译器看不到sendClear。为什么?
问题在于,编译器遇到class template LoggingMsgSender定义式时,并不知道它继承什么样的class。因为MsgSender<Company>中的Company是个template参数,不到后来(当LoggingMsgSender被具现化)无法确切知道它是什么。而如果不知道Company是什么,就无法知道class MsgSender<Company>看起来是个什么样----更明确的说是没办法知道它是否有个sendClear函数。

我按照自己的理解,编写了下面的程序:
class A
{
public:
void funcA()
{
cout<<"funcA"<<endl;
}
};

template<typename T>
class UseA
{
public:
void useAFunc()
{
T a;
a.funcA();
}
};

template<typename T>
class DrivedUseA:public UseA<T>
{
public:
void DrivedUseAFunc()
{
useAFunc();
}
};

但是这个类的使用似乎没什么问题啊?是不是我哪里理解错了?

[解决办法]
与你所使用的编译器选项有关:

error: there are no arguments to 'useAFunc' that depend on a template parameter, so a declaration of 'useAFunc' must be available|
note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)|
||=== Build finished: 1 errors, 0 warnings ===|

读书人网 >C++

热点推荐