【问题标题】:How to pass condition to function? [closed]如何将条件传递给函数? [关闭]
【发布时间】:2020-10-14 12:48:36
【问题描述】:

我想减少重复的代码。下面是一段sn-p代码

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 创建一个通用函数,我也可以在其中传递条件。

【问题讨论】:

标签: c++ c++11 c++14


【解决方案1】:

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

【讨论】:

  • 是的,我正在使用具有包含函数的 qt 的 QString 为简单起见,我使用了 std::string。感谢您的快速解决方案
【解决方案2】:

您也可以使用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...
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多