0

我正在尝试创建一个有限状态机层次结构类型结构。我要做的是检查当前状态是否存在,如果它不返回,然后检查是否所有下一个状态都存在。一旦其中一个失败,它也会返回。

我不确定是否可以使用折叠表达式或可变参数包扩展来完成,但我一直收到参数包未扩展的错误。我不确定我是否可以这样做,或者我是否需要一个辅助函数或其他一些机制。

这是我的方法:

template<unsigned N>
class FSM {
public:
    std::vector<State<N>> states;

    // ... other parts of class

    template<typename Current, typename... NextStates>
    void addStateTransition(Current* currentState, NextStates*... nextStates) {
        // look to see if the current state is a state in our container.
        auto current = std::find(states.begin(), states.end(), currentState);
        if (current == states_.end()) {
            std::cout << "Could not find " << currentState->id_ << " in this State Machine.";
            return;
        }

        // Able to use fold expressions or not to check if all of the next states are in our container?
        auto next = std::find(states.begin(), states.end(), nextStates); 
        // ? I've tried the ellipsis inside, outside and on both sides of the ending parenthesis, and none of them work. 
        if (next == states.end()) {
            std::cout << "Could not find " << nextStates->id_ << " in this State Machine.";
            return;
        }

        // if all of nextStates... are found, do something else here
    }
};
4

1 回答 1

1

要使用折叠表达式,您需要一些可以折叠的东西。您需要为参数包中的每个元素设置一些表达式。您需要的表达式很复杂:调用std::find、检查结果等。因此最好将其粘贴在 lambda 中:

auto lookup = [&](auto nextState) {
    // one single find
    auto it = std::find(states.begin(), states.end(), nextState); 
    if (it == states.end()) {
        std::cout << "Could not find " << nextState->id_ << " in this State Machine.";
        return false;
    }        
    return true;
};

// fold over that
bool const allFound = (lookup(nextStates) && ...);

allFoundtrue如果找到所有状态,或者false至少缺少一个状态,则将是……在这种情况下,将记录一些内容。这也可以处理空包...如果nextStates...是空的,allFound则很简单true

于 2019-08-20T14:04:58.460 回答