c++ - 搜索参数空间时避免嵌套 for 循环

标签 c++ c++11 for-loop idioms

在编写单元测试时,我经常想调用带有参数组合的函数。例如,我有一个函数声明为

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 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186904/

相关文章:

java - 在循环中使用对象名称作为变量

java - 在 AtomicInteger.addAndGet(int) 中使用无限循环

c++ - 排序时如何找出 "progress"?

c++ - 如何在自己的定义中缩写类名?

c++ - 在构造函数中初始化一个 const 数组

c - 这个 for 循环中缺少什么

c++ - 仅在一个 cpp 文件中使用的常量变量 - 在哪里声明它们

c++ - Windows 文件 mfreadwrite.h 出错

c++ - 为什么 Boost.Range is_sorted 不需要前向迭代器?

c++ - 在编译时在 C++ 中生成随机数