搜索参数空间时避免嵌套的 for 循环
Avoid nested for-loops when searching parameter space
在编写单元测试时,我经常想调用一个带有参数组合的函数。例如,我有一个声明为
void tester_func(int p1, double p2, std::string const& p3);
和一些选定的参数
std::vector<int> vec_p1 = { 1, 2, 666 };
std::vector<double> vec_p2 = { 3.14159, 0.0001 };
std::vector<std::string> vec_p3 = { "Method_Smart", "Method_Silly" };
我目前所做的只是
for(auto const& p1 : vec_p1)
for(auto const& p2 : vec_p2)
for(auto const& p3 : vec_p3)
tester_func(p1, p2, p3);
但是,Sean Parent建议避免显式循环,而是使用std::
算法。在上述情况下,如何遵循此建议?有什么成语吗?编写执行此操作的可变参数模板的最干净方法是什么?没有 C++11 功能的最佳方法是什么?
@Oberon的评论中提到了非常好的解决方案。
但我认为这个问题有许多不同的解决方案。这是我的解决方案:
#include <tuple>
#include <type_traits>
template <class TestFunction, class... Containers, class... Types>
typename std::enable_if<sizeof...(Containers) == sizeof...(Types)>::type
TestNextLevel
(
TestFunction testFunction,
const std::tuple<Containers...>& containersTuple,
const Types&... parameters
)
{
testFunction(parameters...);
}
template <class TestFunction, class... Containers, class... Types>
typename std::enable_if<(sizeof...(Containers) > sizeof...(Types))>::type
TestNextLevel
(
TestFunction testFunction,
const std::tuple<Containers...>& containersTuple,
const Types&... parameters
)
{
for (const auto& element : std::get<sizeof...(Types)>(containersTuple))
{
TestNextLevel(testFunction, containersTuple, parameters..., element);
}
}
template <class TestFunction, class... Containers>
void TestAllCases
(
TestFunction testFunction,
const Containers&... containers
)
{
TestNextLevel
(
testFunction,
std::tuple<const Containers&...>(containers...)
);
}
使用示例:
TestAllCases(tester_func, vec_p1, vec_p2, vec_p3);
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式