c++在一个类中使用模板和虚拟方法
c++ using template and virtual method in one class
我有一点继承/模板问题。我正在尝试创建一个由TcpClient
和TcpServer
实现的接口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级别使用的流类型创建抽象。
相关文章:
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 使用模板而不是虚拟方法的管道模式
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 为什么调用没有正文的纯虚拟方法不会导致链接器错误?
- 出于什么目的,非虚拟方法将与C++一起使用?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 如何重写继承的嵌套类中存在的虚拟方法
- 私有虚拟方法有什么用?
- 派生类中纯虚拟基方法的专业化
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 确保模拟的 GTest 方法覆盖虚拟方法
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 如何调用孩子的方法:虚拟关键字不起作用