我有一點遺傳/模板問題。我試圖創建一個接口IBinding
,它由TcpClient
和TcpServer
(將會有2-3個不同的TcpServers,它們只在接受連接請求後產生的流類型(套接字抽象)不同。C++在一個類中使用模板和虛擬方法
下面是一個簡化的例子:
接口:
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()
,但他們應該創建不同類型的流。
一個)據我所知,這是不可能的類型傳遞給bind()
方法在C++中試圖定義bind
方法模板也不起作用參數
b)中,因爲它是虛擬
template<class TSocket>
virtual void bind(const std::string endpoint);
三)我很可能只是創建的TcpServer
兩種不同的實現有另一種方式?沒有辦法用模板做到這一點嗎?
[OT]:你可能想'const std :: string&'而不是'const std :: string'。 – Jarod42
如果'bind'方法不能既是'template'又是'virtual',類'TcpServer'可能是帶'virtual'方法bind的模板。 – Jarod42