The usage of c/c + + overloaded operator standard library function

The usage of overloaded operator standard library function

Question: is int(int, int) a common type??

For example, function: int add(int a, int b);

For example, lambda: Auto mod = [] (int a, int b) {return a% B};

For example, function object class: int operator()(int a, int b);

The common characteristics of the above three are: int(int, int), but how to make the above three forms become common???

Answer: use the function class.

std::function<int(int, int)> f1 = add;
std::function<int(int, int)> f2 = mod;
std::function<int(int, int)> f3 = divide();
std::cout << f1(1,2) << std::endl;
std::cout << f2(4,3) << std::endl;
std::cout << f3(6,2) << std::endl;

Example: suppose that some processing parameters are always 2 ints and the return value is always int. you want to put these processing in a function table, such as square to std::map.

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

int add(int a, int b){
  return a+ b;
}
auto mod = [](int a, int b){return a % b;};
struct divide{
  int operator()(int a, int b){
    return a / b;
  }
};

int main(){
  /*
  std::map<std::string, int(*)(int, int)> mp;
  mp.insert({"+", add});
  mp.insert({"%", mod});
  divide dv;
  mp.insert({"/", divide()});//bian yi bu guo
  
  std::function<int(int, int)> f1 = add;
  std::function<int(int, int)> f2 = mod;
  std::function<int(int, int)> f3 = divide();
  std::cout << f1(1,2) << std::endl;
  std::cout << f2(4,3) << std::endl;
  std::cout << f3(6,2) << std::endl;
  */
  
  std::map<std::string, std::function<int(int, int)>> mp;
  mp.insert({"+", add});
  mp.insert({"-", std::minus<int>()});
  mp.insert({"*", [](int a, int b){return a * b;}});
  mp.insert({"%", mod});
  mp.insert({"/", divide()});

  std::cout << mp["+"](1, 2) << std::endl;
  std::cout << mp["-"](3, 2) << std::endl;
  std::cout << mp["*"](2, 2) << std::endl;
  std::cout << mp["/"](100, 2) << std::endl;
  std::cout << mp["%"](31, 15) << std::endl;
}

github

QQ group of mutual learning in c/c + +: 877684253

My wechat: xiaoshitou5854

Tags: C++ Lambda github

Posted on Wed, 04 Dec 2019 09:30:38 -0500 by blacklotus