最好使用传输协议策略来完成此操作:
template<typename Transport>
class service : Transport {
public:
typedef Transport transport_type;
// common code
void do_something() {
this->send(....);
}
};
class tcp {
public:
void send(....) {
}
};
class udp {
public:
void send(....) {
}
};
typedef service<tcp> service_tcp;
typedef service<udp> service_udp;
请注意,这也是多态的。这称为编译时多态性。将策略放入基类将受益于空基类优化。也就是说,你的基类不需要占用任何空间。将策略作为成员设置还有另一个缺点,即您始终必须将工作委托给该成员,随着时间的推移,这可能会变得烦人。这本书现代 C++ 设计深入描述了这种模式。
Ideally, the transport protocol doesn't need to know anything about the protocol above it. But if for some reason you have to get some information about it, you can use the crtp pattern wiki:
template<template<typename Service> class Transport>
class service : Transport<service> {
// since we derive privately, make the transport layer a friend of us,
// so that it can cast its this pointer down to us.
friend class Transport<service>;
public:
typedef Transport<service> transport_type;
// common code
void do_something() {
this->send(....);
}
};
template<typename Service>
class tcp {
public:
void send(....) {
}
};
template<typename Service>
class udp {
public:
void send(....) {
}
};
typedef service<tcp> service_tcp;
typedef service<udp> service_udp;
您不必将模板放入标题中。如果显式实例化它们,您将获得更快的编译时间,因为需要包含的代码更少。将其放入service.cpp中:
template class service<tcp>;
template class service<udp>;
现在,使用服务的代码不需要知道服务的模板代码,因为该代码已经生成到 service.cpp 的目标文件中。