gpt4 book ai didi

c++ - 如何实现编译时的功能单元测试?

转载 作者:行者123 更新时间:2023-11-30 01:54:55 24 4
gpt4 key购买 nike

我正在编写一个函数,它将一个复杂的公式应用于一堆整数。当我进行大量更改时,我总是编译然后在运行时做一堆测试用例以确保我没有破坏任何东西,所以我想“好吧,我会在我的代码中放一些测试用例”。

但这当然是不可取的,因为该函数需要一段时间才能完成它的工作,并且每次我执行该程序时都会运行测试。有什么简单的方法可以自动执行此操作,以便在编译时检查某些情况吗?这是一个小示例,展示了我当前(不太理想的)方法。

#include <iostream>

int binom(int, int);

int main() {
//I don't want these tests to happen at runtime...
bool test1 = (binom(5,2)!=10); //5 choose 2 should be 10
bool test2 = (binom(7,4)!=35); //7 choose 4 should be 35
if (test1 || test2) {
std::cout << "Your algorithm has an error!";
return 0;
}

int n, k;
std::cout << "n: "; std::cin >> n;
std::cout << "k: "; std::cin >> k;
std::cout << n << " choose "
<< k << " is " << binom(n,k);
return 0;
}

int binom(int n, int k) {
if (k > n/2)
k = n-k;
int nCk = 1, i=1;
for ( ; i<=k; ++i) {
nCk *= n-k+i;
nCk /= i;
}
return nCk;
}

(我写的函数比 n choose k 更复杂,我只是想有一个简单的例子来说明我正在尝试做的事情。)我读过单元测试和一些叫做“编译时函数”的东西执行”,但我认为前者不适用,我也不太了解后者,所以我想知道是否有一种简单的方法来理解这些或实现类似的东西。

最佳答案

您可以使用 constexpr 在编译时评估 binom 并使用 static_assert 对其进行测试。请注意,您还需要根据尾递归来表达迭代。对于 binom 示例,这很简单:

#include <iostream>

constexpr int binom_loop(int n, int k, int i, int nCk) {
return i <= k
? binom_loop(n, k, i + 1, nCk * (n-k+i) / i)
: nCk;
}

constexpr int binom(int n, int k) {
return binom_loop(n, k > n/2 ? n-k : k, 1, 1);
}

// assert that the calculation works - at compile-time
static_assert (binom(5, 2) == 10,
"5 choose 2 should be 10");

int main() {
// enum demonstrates that binom() can be evaluated at compile-time
// if called with literal args
enum {
X = binom(5, 2),
};
std::cout << int(X) << '\n'; // prints 10
}

关于c++ - 如何实现编译时的功能单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com