c++ - 如何将条件传递给函数?
问题描述
我想减少重复的代码。下面是一段代码
void f1(string arg)
{
std::map <string,string> topicAndClientIdMap;
for(auto topicAndClientId : topicAndClientIdMap)
{
if(topicAndClientId.second == arg1)
{
//inset in other map
}
}
}
void f2(string arg)
{
std::map <string,string> topicAndClientIdMap;
for(auto topicAndClientId : topicAndClientIdMap)
{
if(topicAndClientId.first.contains(arg1))
{
//insert in other map
}
}
}
我想创建一个通用函数,f1
并且f2
我也可以在其中传递条件。
解决方案
你可以通过一个std::function
,例如
void f(const std::function<bool(string, string)>& doInclude)
{
for (const auto& [key, value] : topicAndClientIdMap)
if (doInclude(key, value))
; // do stuff...
}
这可以称为
f([&arg](const auto&, const auto& value) { return value == arg; });
f([&arg](const auto& key, const auto&) { return key.contains(arg); });
在这里,std::function
参数使用 lambda 表达式初始化,该表达式将过滤检查封装在您的代码片段中 for f1
and f2
(但请注意,我不知道什么string
是 - 如果是std::string
,则没有contains
成员函数,所以上面不会编译,以及您发布的原始片段)。