You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改testMethod,在main保留其调用并借助testMethodOnInt遍历map?

解决方案:通过函数适配实现间接调用

问题描述

我有两个函数testMethodOnInt和testMethod,二者均以std::function作为参数:前者的参数类型是接受int的函数,后者是接受std::pair<std::string, int>的函数。能否在main函数中保留testMethod(lambda);的调用,同时修改testMethod使其调用testMethodOnInt,从而打印map中的每个值?

附加要求:

  • main函数中必须调用testMethod,不可直接调用testMethodOnInt;
  • testMethod不能直接访问map,必须调用testMethodOnInt。

修改后的完整代码

#include <iostream>
#include <functional>
#include <map>
#include <string>

std::map<std::string, int> m { {"CPU", 10}, {"GPU", 15}, {"RAM", 20}, }; 

// This method can't be called in main directly
void testMethodOnInt(std::function<void(int)> f2) {
    for(const auto& item : m) {
       f2(item.second);
    }
}

// this method doesn't have access to the map, but can call testMethodOnInt method 
void testMethod(std::function<void(std::pair<std::string, int>)> f) {
    // 适配接受pair的函数为接受int的函数
    std::function<void(int)> adapted_func = [f](int val) {
        // 构造pair传入原函数,字符串部分不影响原逻辑
        f(std::make_pair("", val));
    };
    testMethodOnInt(adapted_func);
}

int main()
{   
    auto lambda = [](std::pair<std::string, int> x) { std::cout << x.second << std::endl; };
    testMethod(lambda);
}

实现思路

核心是通过函数适配完成类型转换:

  1. 在testMethod内部,创建一个适配函数adapted_func,它接收int类型的值;
  2. 适配函数内部构造一个std::pair<std::string, int>(字符串部分可任意,因为原lambda仅使用pair的第二个元素),并将其传入原函数f;
  3. 将适配后的函数传给testMethodOnInt,由它遍历map的每个值并触发调用,最终执行原lambda的打印逻辑。

这样既满足了main函数不直接调用testMethodOnInt的要求,也保证了testMethod不直接访问map,完全符合约束条件。

内容的提问来源于stack exchange,提问作者PepperGooooo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 05:27:32