c++在一个类中使用模板和虚拟方法

c++ using template and virtual method in one class

本文关键字:方法 虚拟 一个 c++      更新时间:2023-10-16

我有一点继承/模板问题。我正在尝试创建一个由TcpClientTcpServer实现的接口IBinding(将有2-3个不同的TcpServer,它们在接受连接请求后生成的流(套接字抽象)类型不同。

下面是一个简化的例子:

接口:

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(),但它们应该创建不同类型的Streams。

a) 据我所知,在c++中,不可能将Type作为参数传递给bind()方法

b) 尝试定义模板化的bind方法也不起作用,因为它是虚拟

    template<class TSocket>
    virtual void bind(const std::string endpoint);

c) 我可能只需要创建两个不同的TcpServer 实现

还有别的办法吗?难道没有一种方法可以用模板做到这一点吗?

否。模板函数本质上与虚拟调度不兼容。您无法覆盖它们。它们可以隐藏名称,但这可能对你没有帮助。因此,您需要为将要使用的每个流类型提供虚拟函数,或者为可在IBinding级别使用的流类型创建抽象。