Home > Software engineering >  transfer lambda to another lambda with different type
transfer lambda to another lambda with different type

Time:08-05

Suppose I have two functions testMethodOnInt and testMethod, they both take std::function as parameter. One is on type int, the other is on type pair<string, int>.

Is there a way to keep testMethod(lambda); call in main function, but modify testMethod to use testMethodOnInt, so it can print every value in the map.

There are a few additional requirements:

  1. testMethod has to been called in the main function, while testMethodOnInt can't be called in main function
  2. testMethod can't access the map directly, it has to call 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) {
   ..
}

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

CodePudding user response:

You can wrap f with a lambda and forward it to testMethodOnInt.

void testMethod(std::function<void(std::pair<std::string, int>)> f) {
  testMethodOnInt([&](int x) { f({"", x}); });
}
  • Related