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

How to abstract code which calls various other code

我在 CLion 中做了很多项目,每个项目都有两段代码:SolutionTestConductorSolution 是代码型的解决方案,TestConductor 使用 Catch2 来 运行 测试(存储在 input_n.txtoutput_n.txt 文件中)。 TestConductor 当然必须调用 SolutionSolution 每个项目的变化(代表不同的型),但 TestConductor 的变化仅在于它需要知道 input.txtoutput.txt 文件的名称(它们的名称可以略有不同),以及如何调用 Solution(不同的 katas 的名称不同,比如它可以被称为 PermutationFinderPairSorter 或其他)。

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

TestConductor 代码是 here 如果你想要一些具体的。 (45 行)

我想更一般地说,当您想要抽象并在多个项目中重用的代码不是由更改的代码调用,而是调用它时,您会怎么做?

我了解到这是一种相当普遍的情况,并且有一个简单的解决方案。对不起,如果这是一个重复的问题;我不知道我可以使用什么搜索词。

您可以根据其解决方案 class 使 TestConductor 通用,只需像这样更改 class 声明:

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();
    }
}