-3

I want to insert std::function as a std::map key, but the code doesnt compile, any thoughts?

int sum(int a, float b){
    return a+b;
}

int main()
{
    std::function<int(int, float)>f = sum;
    std::map <std::function<int(int, float)>, std::string> mapa;
    mapa.insert(std::make_pair(f, "sum"));
}
black_gay
  • 143
  • 7
  • 2
    but the code doesnt compile - what does it do if it doesn't compile? Any error? – 273K Aug 09 '23 at 19:55
  • 2
    could it be that you want string to be the key and function to be the value? – Raildex Aug 09 '23 at 20:01
  • 1
    This is very unusual. Can you describe what you want the program to do? We may be able to offer alternatives. – user4581301 Aug 09 '23 at 20:20
  • 1
    [yx problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? Could it be that you want a `std::map` ? So that you can look up the function by its name? – 463035818_is_not_an_ai Aug 09 '23 at 20:51

1 Answers1

4

std::map requires ordered keys.

std::function does not support an order.

They can't work together.

Adding ordering requirements to a std::function isn't trivial. I'd advise against trying.

Note that the reversed map has no problems.

std::function doesn't even support ==, let alone < or (for the unordered map) std::hash.

Reconsider your design.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524