首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在一个类中使用模板和虚拟方法的c++

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

Stack Overflow用户
提问于 2016-04-08 18:43:23
回答 1查看 37关注 0票数 1

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

下面是一个简化的示例:

接口:

代码语言:javascript
复制
struct IBinding
    {
        virtual ~IBinding() {}

        virtual void bind(const std::string endpoint) = 0;

        virtual void terminate() = 0;
    };

    typedef std::shared_ptr<IBinding> TBindingPtr;

标题:

代码语言:javascript
复制
#include "IBinding.h"

class TcpServer : public IBinding
{
public:
    TcpServer();
    ~TcpServer();

    virtual void bind(const std::string endpoint);

    virtual void terminate();

};

执行情况:

代码语言:javascript
复制
#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方法也不起作用,因为它是虚拟的

代码语言:javascript
复制
    template<class TSocket>
    virtual void bind(const std::string endpoint);

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

还有别的办法吗?难道没有办法用模板来完成吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-08 18:49:57

不是的。模板函数与虚拟调度本质上是不兼容的。你不能推翻他们。他们可以是隐藏的名字,但这可能帮不了你。因此,您需要为将要使用的每个流类型提供虚拟函数,或者为可以在IBinding级别上使用的流类型创建一个抽象。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36507009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档