Bee*_*ope 4 c++ templates c++11
我有一个类型为type的非类型模板参数的函数int,如下所示:
template <int N>
int foo() { /*...*/ }
Run Code Online (Sandbox Code Playgroud)
我想对该函数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
Run Code Online (Sandbox Code Playgroud)
我不想手工写出所有33个测试用例,而且由于N编译时的原因,我不能轻易使用运行时循环。
如何BOOST_PP_REPEAT在C ++ 11中让编译器以简单的方式为我生成测试用例,而无需-style技巧或代码生成?
您可以编写具有完全专业知识的递归函数模板来执行测试。例如
template <int N>
void test() {
test<N-1>();
if (foo<N>() != expected(N)) { /* fail... */ }
}
template <>
void test<-1>() {
// do nothing
}
Run Code Online (Sandbox Code Playgroud)
然后像这样运行
test<32>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |