You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:54:27