c – 搜索参数空间时避免使用嵌套的for循环
发布时间:2020-12-16 07:07:21 所属栏目:百科 来源:网络整理
导读:在编写单元测试时,我经常想要使用参数组合来调用函数.例如,我有一个声明为的函数 void tester_func(int p1,double p2,std::string const p3); 和一些选定的参数 std::vectorint vec_p1 = { 1,2,666 };std::vectordouble vec_p2 = { 3.14159,0.0001 };std::ve
在编写单元测试时,我经常想要使用参数组合来调用函数.例如,我有一个声明为的函数
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... Types> typename std::enable_if<(sizeof...(Containers) > sizeof...(Types))>::type TestNextLevel ( TestFunction testFunction,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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |