簡體   English   中英

搜索參數空間時避免使用嵌套的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:: algorithms。 如何在上述案例中遵循這一建議? 有成語嗎? 編寫可執行模板的變量模板的最簡潔方法是什么? 沒有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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM