std::function as a std::map key

90 Views Asked by At

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"));
}
1

There are 1 best solutions below

0
Yakk - Adam Nevraumont On BEST ANSWER

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.