如何解决C++模板参数循环依赖及简化单元测试实例化?
问题描述
我正在对类TestingThis进行单元测试,该类包含一个以TestingThis为模板参数的Socket(用于回调):
class TestingThis { TestingThis() : _socket(*this){} Socket<SocketType, TestingThis> _socket; };
为了在单元测试中Mock这个Socket,我将Socket类型设为TestingThis的模板参数:
template<class SOCKET> class TestingThis { TestingThis() : _socket(*this){} SOCKET _socket; };
但由于生产环境中的Socket本身就以TestingThis为模板参数,实例化TestingThis时会出现模板参数无限递归:
TestingThis<Socket<SocketType, TestingThis<Socket<.......无限循环......>>>> productionInstance; ^ 问题所在
请问最佳处理方式是什么?
更新内容
目前我已实现如下实例化方式:
TestingThis<Socket, NoSSL> production; TestingThis<Socket, OpenSSL> production; TestingThis<Socket, AnotherSSL> production;
但测试时无需关注具体实现,更希望采用如下实例化方式:
TestingThis<MockSocket> testing;
同时生产环境的实例化为:
TestingThis<Socket<NoSSL>> production; TestingThis<Socket<OpenSSL>> production; TestingThis<Socket<AnotherSSL>> production;
内容的提问来源于stack exchange,提问作者user997112
相关产品推荐
相关产品推荐

