With this following code:
#include <map>
#include <functional>
#include "main.h"
std::map<int,std::function<void()>> fnc_event_to;
void testFunction();
void initialize() {
fnc_event_to[1] = testFunction;
bool boolean = fnc_event_to[2] == testFunction;//<- error
pros::lcd::initialize();
pros::lcd::print(2,"%d",boolean);
}
I recieve this error:
invalid operands to binary expression ('std::map<int, std::function<void ()>, std::less<int>, std::allocator<std::pair<const int, std::function<void ()> > > >::mapped_type' (aka 'std::function<void ()>') and 'void (*)()')
How come I can assign the function pointer to the map but I am not able to compare it with a function pointer?
Also, if a key is not defined, what will the map return?
Is there a way to compare the std::function
so I can see whether its a null function pointer or is it defined already?
Or is there a better solution for this? Originally, I'm using a while(1)
loop to trap the thread and the map is just a map of what the program should do when a variable reaches the key(int). The variable is changed in a separate task so its multitasking. I couldn't use the .contains()
method since I'm not using C++ 20 yet.
This is just posted for reference. Answers are quoted from @0x499602D2 and @LightnessRacesInOrbit. Either use:
if (fnc_event_to[2]){
}
Or
if(fnc_event_to.find(2) != fnc_event_to.end()){
}
Be aware that the first option will create an empty element, so if you give the map the same value, it will already be created, and it will return true.