如何解决如何通过条件发挥作用?
我想减少重复的代码。下面是一段代码
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表达式初始化的,该表达式封装了f1
和f2
的摘要中的过滤检查(但请注意,我不知道{{ 1}}是-如果它是string
,则没有std::string
成员函数,因此上面的内容以及您发布的原始代码段都不会编译。
您也可以使用template。
// only a demo snippet
using std::string;
std::map<string,string> topicAndClientIdMap;
// Initiate topicAndClientIdMap with some data
template <typename FUNC>
void TmplF(std::string& arg,FUNC f) {
for (auto& topicAndClientId : topicAndClientIdMap) {
f(topicAndClientId)
}
// other operations...
}
int main() {
std::string arg = "str";
TmplF(arg,[&arg](std::pair<string,string>& p) {
if (p.second == arg) {
// do whatever you want...
}
});
TmplF(arg,string>& p) {
if (p.first.contains(arg)) {
// do whatever you want...
}
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。