【发布时间】:2019-10-06 12:36:51
【问题描述】:
我正在编写一个“设备驱动程序”(C++14),它可以处理用于不同版本设备的多个版本的协议。此设备驱动程序在外部 PC 上运行,该 PC 使用基于 HTTP 的协议通过以太网与设备通信。所有版本都有共同的功能,但某些功能可能会在某些版本的协议中增加。
下面是一个例子:
class ProtocolBase {
public:
virtual void reset_parameters() {
std::cout << "reset parameters" << std::endl;
}
virtual void set_parameters() {
std::cout << "set parameters" << std::endl;
}
};
class ProtocolV1 : public ProtocolBase
{
public:
void set_parameters() override {
std::cout << "set parameters for V1" << std::endl;
}
};
class ProtocolV2 : public ProtocolBase
{
public:
void set_parameters() override {
std::cout << "set parameters for V2" << std::endl;
}
void reset_parameters() {
std::cout << "reset parameters for V2" << std::endl;
}
void do_V2() {
std::cout << "doing V2" << std::endl;
}
};
下面是main:
int main(int argc, char const *argv[])
{
int version = std::atoi(argv[1]);
std::unique_ptr<ProtocolBase> protocol = std::make_unique<ProtocolV1>();
switch (version)
{
case 1:
/* do nothing at the moment */
break;
case 2:
protocol.reset(new ProtocolV2);
break;
default:
break;
}
protocol->reset_parameters();
if(ProtocolV2* p = dynamic_cast<ProtocolV2*>(protocol.get())) { //not sure about this
p->do_V2();
}else {
std::cout << "This functionality is unavailable for this device" << std::endl;
}
protocol->set_parameters();
return 0;
}
我感觉使用dynamic_cast 不是最好的方法。期待一些反馈。
编辑:根据@Ptaq666 的回答,我将ProtocolBase 和ProtocolV2 修改为:
class ProtocolBase {
public:
virtual void do_V(){
std::cerr << "This functionality is unavailable for this device" << std::endl;
}
};
class ProtocolV2 : public ProtocolBase
{
public:
void do_V() override {
std::cout << "doing V2" << std::endl;
}
};
有了这个,就不再需要dynamic_cast,尽管基类必须知道所有的功能。这似乎是目前最好的解决方案。
【问题讨论】:
-
很好的例子在这里:cs.chromium.org/chromium/src/third_party/blink/public/platform/… 输入事件类型(在您的情况下是协议版本)在输入事件构造中指定。输入事件类型由
IsMouseEventType等方法确定,在您的情况下为IsProtocolV2 -
还有什么是
Protocol在主要的第二行std::unique_ptr<Protocol> protocol = std::make_unique<ProtocolV1>();你的意思是ProtocolBase吗? -
我的错,是的,我的意思是
ProtocolBase -
感谢您的澄清!如果函数不依赖于派生类中可能不同的任何数据成员,我看不出有任何问题!您不确定的是什么?你有什么顾虑?
-
@Fareanor 你是对的,但在这种特定情况下,这并不重要!
标签: c++ architecture version driver