【问题标题】:C++ error:[ invalid operands to binary expression ('std::map<int, std::function<void ()>, std::less<int>...]C++ 错误:[二进制表达式的无效操作数 ('std::map<int, std::function<void ()>, std::less<int>...]
【发布时间】:2019-07-23 15:00:56
【问题描述】:

使用以下代码:

#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);
}

我收到此错误:

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 (*)()')

为什么我可以将函数指针分配给映射,但我无法将其与函数指针进行比较?

另外,如果没有定义键,映射会返回什么?

有没有办法比较std::function,以便我可以看到它是空函数指针还是已经定义?

或者有更好的解决方案吗?最初,我使用while(1) 循环来捕获线程,并且映射只是当变量到达键(int)时程序应该做什么的映射。该变量在单独的任务中更改,因此它是多任务处理。我不能使用.contains() 方法,因为我还没有使用 C++ 20。

【问题讨论】:

  • 你试过fnc_event_to[2] == std::function&lt;void()&gt;(testFunction)吗?无论如何,您可能会感到失望,因为所有非空 std::function 对象比较不相等。
  • 我试过std::function&lt;void()&gt;(testFunction),它显示这个错误:invalid operands to binary expression ('std::map&lt;int, std::function&lt;void ()&gt;, std::less&lt;int&gt;, std::allocator&lt;std::pair&lt;const int, std::function&lt;void ()&gt; &gt; &gt; &gt;::mapped_type' (aka 'std::function&lt;void ()&gt;') and 'std::function&lt;void ()&gt;')
  • 不能使用.contains() 方法真的很遗憾。这会让我的生活轻松很多。还是不支持c++ 20
  • 或者有更好的解决方案吗?最初,我使用 while(1) 循环来捕获线程,并且映射只是当变量到达键(int)时程序应该做什么的映射。该变量在单独的任务中更改,因此它是多任务处理。我无法使用.contains()method,因为我还没有使用 c++ 20

标签: c++ function function-pointers stdmap std-function


【解决方案1】:

此贴仅供参考。答案来自@0x499602D2 和@LightnessRacesInOrbit。 要么使用:

if (fnc_event_to[2]){
}

或者

if(fnc_event_to.find(2) != fnc_event_to.end()){
}

请注意,第一个选项将创建一个空元素,因此如果您为地图提供相同的值,则它已经被创建,并且将返回 true。

【讨论】:

  • 正确 - 但请注意,如果元素尚不存在,第一个示例将 创建(通过默认构造),因此第二个示例在此之后将不起作用.您可能希望区分包含“空”函数的映射和不包含函数的映射。
  • 谢谢!不知道以后调试会很辛苦!
【解决方案2】:

标准类 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;

所以只能检查类的一个对象是否为“空”。

【讨论】:

  • 对不起,我对 C++ 很陌生,那么我应该把比较的 rside 放在什么地方?
  • 你应该改为这样做,这样你就不需要比较了。为什么你认为你需要比较?
  • @LightnessRacesinOrbit 我只需要检查地图中的 std::function 是否存在,因为我将从地图上的传感器中抛出随机数,直到其中一个有效,然后运行该函数。还是您提出更好的解决方案? (见我的帖子底部)
  • @Arandomprogramer 您的代码尝试查看该函数是否与另一个函数相同,而不是它是否“存在”。你想要的是哪一个?你所说的“存在”是什么意思?你能举一个不存在的函数的例子吗?你的意思是默认构造的std::function
  • @LightnessRacesinOrbit 不存在,我的意思是密钥未定义。假设我在地图中声明了一个项目:fnc_event_to[1] = test function。当我给未定义的映射键(如fnc_event_to[2])时,如何测试该键是否存在?
猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多