gpt4 book ai didi

c++ - 使用非类型模板参数重复调用函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:21:36 25 4
gpt4 key购买 nike

我有一个带有 int 类型的非类型模板参数的函数,如下所示:

template <int N>
int foo() { /*...*/ }

我想针对 N 从 0 到 32 的所有值对该函数进行单元测试。我有一个函数 int expected(int n) 接受相同的 N 值并返回期望值。实际上,我想要:

if (foo<0>() != expected(0)) { /* fail... */ }
if (foo<1>() != expected(1)) { /* fail... */ }
if (foo<2>() != expected(2)) { /* fail... */ }
// 30 more lines

我不想手写所有 33 个测试用例,而且我不能轻易使用运行时循环,因为 N 是编译时间。

在 C++11 中,如何让编译器以简单的方式为我生成测试用例,而不需要 BOOST_PP_REPEAT 风格的技巧或代码生成?

最佳答案

您可以使用 full specialization 编写递归函数模板执行测试。例如

template <int N>
void test() {
test<N-1>();
if (foo<N>() != expected(N)) { /* fail... */ }
}

template <>
void test<-1>() {
// do nothing
}

然后像这样运行

test<32>();

关于c++ - 使用非类型模板参数重复调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57518416/

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