std::variant 之前的声明符无效

invalid declarator before std::variant

我正在尝试使用 std::variant 实现一个临时的轻量级状态机。但是,变体 fsm 似乎未正确声明,因为它因以下错误而失败:

<source>: In function 'int main()':
<source>:235:40: error: invalid declarator before 'fsm'
  235 |     std::variant<states::A, states::B> fsm{std::in_place_index<0>};
      |                                        ^~~
<source>:238:5: error: 'fsm' was not declared in this scope
  238 |     fsm = std::visit([&](auto&& state){ state.on_event(eWifi::connected); }, fsm);
      |     ^~~
ASM generation compiler returned: 1
<source>: In function 'int main()':
<source>:235:40: error: invalid declarator before 'fsm'
  235 |     std::variant<states::A, states::B> fsm{std::in_place_index<0>};
      |                                        ^~~
<source>:238:5: error: 'fsm' was not declared in this scope
  238 |     fsm = std::visit([&](auto&& state){ state.on_event(eWifi::connected); }, fsm);
      |     ^~~

我真的搞不懂哪里出了问题。这是代码:

#include <iostream>
#include <variant>

enum class eWifi {
    connected,
    disconnected,
};

enum class eMQTT {
    connected,
    disconnected,
};

int main()
{
    // int a;

    struct states {
        struct A {
            auto on_event(eWifi evt) {
                std::cout << "on_event A" << std::endl;
                return B{};
            }
            auto on_event(eMQTT evt) {
                std::cout << "on_event A" << std::endl;
                return B{};
            }
        };

        struct B {
            auto on_event(eWifi evt) {
                std::cout << "on_event B" << std::endl;
                return A{};
            }
            auto on_event(eMQTT evt) {
                std::cout << "on_event B" << std::endl;
                return A{};
            }
        };
    }


    std::variant<states::A, states::B> fsm{std::in_place_index<0>};

    // while(1) {
    fsm = std::visit([&](auto&& state){ state.on_event(eWifi::connected); }, fsm);
    // }
}

'fsm' 之前的无效声明符是什么意思?

  1. 您在 struct states 的声明中漏掉了分号。
    struct states {
        struct A {
        };

        struct B {
        };
    };
  1. 您忘记 return 您的 lambda 函数中的结果。
fsm = std::visit([&](auto&& state) -> std::variant<states::A, states::B> {
                return state.on_event(eWifi::connected); 
            }, fsm);

demo