mardi 4 août 2020

Can std::function store different function signatures in C++

I have some functions with the same parameter types and numbers, but different return value types. In order to find these functions, I use map to store their mapping relationship, but for this I have to define two maps. code as below:

double func_double1(int a, int b) {
  return 0.0;
}

double func_double2(int a, int b) {
  return 0.0;
}

int func_int1(int a, int b) {
  return 0;
}

int func_int2(int a, int b) {
  return 0;
}

using GetDouble = std::function<double(int, int)>;
using GetInt = std::function<int(int, int)>;

std::unordered_map<std::string, GetDouble> double_factory = {
    {"func_double1", func_double1},
    {"func_double2", func_double2}
};

std::unordered_map<std::string, GetInt> double_factory = {
    {"func_int1", func_int1},
    {"func_int2", func_int2}
};

Can std::function store different function signatures?

Can I use generics to solve this problem?

Or is there a better way?

Aucun commentaire:

Enregistrer un commentaire