[英]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? 有没有一种方法可以比较
std::function
所以我可以看到它是一个空函数指针还是已经定义了?
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). 最初,我使用
while(1)
循环来捕获线程,并且映射只是当变量到达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. 由于尚未使用C ++ 20,因此无法使用
.contains()
方法。
This is just posted for reference. 这只是发布以供参考。 Answers are quoted from @0x499602D2 and @LightnessRacesInOrbit.
答案引用自@ 0x499602D2和@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. 请注意,第一个选项将创建一个空元素,因此,如果为地图赋予相同的值,则将已经创建它,并且它会返回true。
The standard class std::function has only these comparison operator == 标准类std :: function只有这些比较运算符==
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". 因此,您只能检查该类的对象是否为“空”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.