我有一点继承/模板问题。我正在尝试创建一个接口IBinding,它由一个TcpClient和一个TcpServer实现(将有2-3个不同的TcpServers,它们在接受连接请求后生成的流(套接字抽象)的类型不同。
下面是一个简化的示例:
接口:
struct IBinding
{
virtual ~IBinding() {}
virtual void bind(const std::string endpoint) = 0;
virtual void terminate() = 0;
};
typedef std::shared_ptr<IBinding> TBindingPtr;标题:
#include "IBinding.h"
class TcpServer : public IBinding
{
public:
TcpServer();
~TcpServer();
virtual void bind(const std::string endpoint);
virtual void terminate();
};执行情况:
#include "TcpServer.h"
#include "StreamTypeA.h"
#include "StreamTypeB.h"
TcpServer::TcpServer() { }
TcpServer::~TcpServer() { }
void TcpServer::terminate() { }
void TcpServer::bind(const std::string endpointStr)
{
auto stream = std::make_shared<StreamTypeA>(); // Here I need to use different types depending on the server implementation
} 现在,我想创建两个TcpServer实例并对它们调用.bind(),但是它们应该创建不同类型的流。
( a)据我所知,不可能将类型传递给bind()方法作为c++中的参数
( b)尝试定义模板化的bind方法也不起作用,因为它是虚拟的
template<class TSocket>
virtual void bind(const std::string endpoint);c)我可能只需要创建两个不同的TcpServer实现
还有别的办法吗?难道没有办法用模板来完成吗?
发布于 2016-04-08 18:49:57
不是的。模板函数与虚拟调度本质上是不兼容的。你不能推翻他们。他们可以是隐藏的名字,但这可能帮不了你。因此,您需要为将要使用的每个流类型提供虚拟函数,或者为可以在IBinding级别上使用的流类型创建一个抽象。
https://stackoverflow.com/questions/36507009
复制相似问题