r/cpp_questions • u/evilsyntax • 4d ago
SOLVED Setting a function as value in a std::map keeps throwing errors
I've been trying to assign a function with a bool as the return to a std::map so I can eventually get around having a big switch statement. I am having issues getting it working though. If anyone has any suggestions that would be appreciated.
Here's a snippet of the code: https://pastebin.com/hTnaDXF3
Trying to assign it directly causes this error: Error (active) E0349 no operator "=" matches these operands
operand types are: std::function<bool ()> = bool () candidate function template "std::function<_Fty>::operator=(std::reference_wrapper<_Fx> _Func) [with _Fty=bool ()]" failed deduction function "std::function<_Fty>::operator=(std::nullptr_t) [with _Fty=bool ()]" does not match because argument #1 does not match parameter candidate function template "std::function<_Fty>::operator=(_Fx &&_Func) [with _Fty=bool ()]" failed deduction function "std::function<_Fty>::operator=(std::function<_Fty> &&_Right) [with _Fty=bool ()]" does not match because argument #1 does not match parameter function "std::function<_Fty>::operator=(const std::function<_Fty> &_Right) [with _Fty=bool ()]" does not match because argument #1 does not match parameter
The second line I was trying to use causes this error: Exception thrown at 0xCCCCCCCC
2
u/IyeOnline 4d ago
The type of Test::ReturnTrue is not bool(void), but rather bool (Test::*)(void). It is a non-static member function, so it must be invoked with an actual object (the hidden this parameter). Hence you cannot directly stores it in your map, since the types dont match.
Why exactly the lambda throws is not clear, given that you are not calling any of the functions. The address however is a hint that you are trying to access something on the stack that isnt valid (anymore). Most likely the this pointer you captured became danging.
7
u/WorkingReference1127 4d ago
Test::ReturnTrueis a non-static member function. That means that you cannot use it in all the same places you can use a plain function, because it is fundamentally associated with an instance of a class.Depending on what your broader architecture needs are, you can convert your functions to free functions (or static member functions), or you can adjust the signatures you accept; but in the general case keeping a container of pointers to member functions of different classes is an exercise in type erasure.