如何抽象调用其他各种代码的代码

问题描述

我正在CLion中做很多项目,每个项目都有两段代码SolutionTestConductorSolution代码选项卡的解决方案,TestConductor使用Catch2运行测试(存储在input_n.txtoutput_n.txt文件中)。当然,TestConductor必须致电SolutionSolution针对每个项目(代表不同的kata)而变化,但是TestConductor的变化之处在于它需要知道input.txtoutput.txt文件名称(它们的名称可以略有不同),以及如何调用Solution(对于不同的kata,其名称是不同的,例如可以称为PermutationFinderPairsorter或其他名称)。

我基本上已经将TestConductor代码复制粘贴到我的每个项目中,这对我来说似乎很臭。在哲学上正确的方法是什么?使TestConductor成为某种类型的库? (仍然学习如何制作和使用它们。)

如果需要一些具体说明,

TestConductor代码here。 (45行)

我更一般地说,当要抽象并在多个项目中重用的代码没有被更改的代码调用而是被调用时,该怎么办?

我知道这是一种非常常见的情况,有一个简单的解决方案。很抱歉,如果这是重复的问题;我不知道可以使用哪些搜索字词。

解决方法

您可以根据其Solution类使TestConductor通用,只需像这样更改类声明即可:

template <class Solution>
class TestConductor { ... };

然后,声明可以进入一个头文件,您可以将其包含在各个项目中。

然后在每个项目中,您可以将测试用例提供为:

TEST_CASE() {
    TestConductor<PermutationFinder> testMaker;
    for (int test_number = 1; test_number <= 5; test_number++) {
        string solution = testMaker.get_solution(test_number);
        string test_solution = testMaker.get_test_solution(test_number);
        REQUIRE(solution == test_solution);
        testMaker.reset();
    }
}