I am trying to insert a function into a map but I want to check it first so I would like to overload assignment operation for std::function, is this possible?
I try to overload the assignment operation, so if something other than expected is assigned, the assignment operator function should wrap it in the expected function and return it.
#include <iostream>
#include <map>
#include <functional>
class MyClass{
public:
std::map<int, std::map<int, std::function<void(int,int)>>> events;
std::function<void(int,int)>& on(int type, int id){ return events[type][id]; };
template<typename T> std::function<void(int,int)>& operator= (T&& fn){
std::wcout << L"assigning correct function\n";
return [&](int x, int y){
if(typeid(fn)==typeid(std::function<void(int,std::wstring)>)) fn(x, L"two");
};
}
};
int main(int argc, char **argv)
{
MyClass obj;
obj.on(1,2) = [](int x, int y){ std::wcout << L"int " << x << L" " << y << std::endl; }; //this works but it's not calling the overload operator
obj.on(1,2) = [](int x, std::wstring y){ std::wcout << L"string " << x << L" " << y << std::endl; }; //I need this to work too
obj.events[1][2](2,3);
return 0;
}
Output:
test.cpp:23:14: error: no match for 'operator=' (operand types are 'std::function<void(int, int)>' and 'main(int, char**)::<lambda(int, std::__cxx11::wstring)>')
obj.on(1,2) = [](int x, std::wstring y){ std::wcout << L"string " << x << L" " << y << std::endl; };
^
Sounds like what you need is a proxy class. The problem is, when you return a
std::function<..>&
fromon()
, you end up with astd::function
. You can't overwrite that class'soperator=
, which is what I think you're trying to do. Instead, you're overwritingMyClass::operator=
- which is a function you're never actually calling.Instead, return a proxy whose assignment you can control. Something like this:
And then we can provide special overloads for
Proxy::operator=
. The "valid, correct type" case:and the
wstring
case:With that, your original
main()
will compile and do what you expect.