为什么我不能调用这个 lambda 函数?

问题描述 投票:0回答:1

下面是导致问题的代码部分的简化版本:

void reorient(C new_pos) {

  // Orientate north
  if (pos + 0x10 == new_pos) {
    if ((orient == 0) && (Gz < 0.1 || Gz > 2 * PI - 0.1)) return;
    auto disoriented = []() {return Gz < PI;};
    orient = 0;

  // Orientate east
  } else if (pos + 0x01 == new_pos) {
    if ((orient == 1) && (abs(Gz - HALF_PI) < 0.1)) return;
    auto disoriented = []() {return Gz < HALF_PI || Gz > 3 * HALF_PI;};
    orient = 1;

  // Orientate south
  } else if (pos - 0x10 == new_pos) {
    if ((orient == 2) && (abs(Gz - PI) < 0.1)) return;
    auto disoriented = []() {return Gz > PI;};
    orient = 2;

  // Orientate west
  } else {
    if ((orient == 3) && (abs(Gz - HALF_PI * 3) < 0.1)) return;
    auto disoriented = []() {return Gz > HALF_PI && Gz < 3 * HALF_PI;};
    orient = 3;
  }

  disoriented();
}

由于某种原因,我收到编译错误:

Compilation error: 'disoriented' was not declared in this scope

Gz
PI
HALF_PI
pos
都是全局变量(我使用的是arduino)。 当我在每个 if 语句中移动
disoriented()
时,此错误就会消失,并且代码中的其他任何地方都不会调用
disoriented()
。怎么了?

c++ c++11 lambda
1个回答
0
投票

您在每个

if
/
else
块内声明一个单独的 lambda 实例。在您尝试调用其中任何一个之前,它们都超出了范围。

要执行您正在尝试的操作,您需要在第一个

disoriented
之前将
if
声明为其自己的变量。但是,由于每个 lambda 都是不同的编译器生成的类型,因此您必须将
disoriented
声明为可以处理所有这些的单一类型。您可以使用
std::function
或函数指针(因为您的 lambda 都没有捕获值),例如:

#include functional>

void reorient(C new_pos) {

  std::function<void()> disoriented;

  // Orientate north
  if (pos + 0x10 == new_pos) {
    ...
    disoriented = []() {return Gz < PI;};
    ...

  // Orientate east
  } else if (pos + 0x01 == new_pos) {
    ...
    disoriented = []() {return Gz < HALF_PI || Gz > 3 * HALF_PI;};
    ...

  // Orientate south
  } else if (pos - 0x10 == new_pos) {
    ...
    disoriented = []() {return Gz > PI;};
    ...

  // Orientate west
  } else {
    ...
    disoriented = []() {return Gz > HALF_PI && Gz < 3 * HALF_PI;};
    ...
  }

  disoriented();
}

或者:

void reorient(C new_pos) {

  void (*disoriented)();

  // Orientate north
  if (pos + 0x10 == new_pos) {
    ...
    disoriented = +[]() {return Gz < PI;};
    ...

  // Orientate east
  } else if (pos + 0x01 == new_pos) {
    ...
    disoriented = +[]() {return Gz < HALF_PI || Gz > 3 * HALF_PI;};
    ...

  // Orientate south
  } else if (pos - 0x10 == new_pos) {
    ...
    disoriented = +[]() {return Gz > PI;};
    ...

  // Orientate west
  } else {
    ...
    disoriented = +[]() {return Gz > HALF_PI && Gz < 3 * HALF_PI;};
    ...
  }

  (*disoriented)();
}
© www.soinside.com 2019 - 2024. All rights reserved.