如何将条件传递给函数?

How to pass condition to function?

我想减少重复代码。下面是一段代码

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
           }
        }

}

我想为 f1f2 创建一个通用函数,我也可以在其中传递条件。

您可以传递 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 表达式初始化,该表达式封装了 f1f2 片段中的过滤检查(但请注意,我不知道是什么string 是 - 如果它是 std::string,它没有 contains 成员函数,所以上面的代码将无法编译,以及您发布的原始片段)。

您也可以使用 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, [&arg](std::pair<string, string>& p) {
        if (p.first.contains(arg)) {
            // do whatever you want...
        }
    });
}