简体   繁体   中英

C++ error:[ invalid operands to binary expression ('std::map<int, std::function<void ()>, std::less<int>…]

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.

The standard class std::function has only these comparison operator ==

template<class R, class... ArgTypes>
bool operator==(const function<R(ArgTypes...)>&, nullptr_t) noexcept;

template<class R, class... ArgTypes>
bool operator==(nullptr_t, const function<R(ArgTypes...)>&) noexcept;

So you can only check whether an object of the class is "empty".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM