Search code examples
c++templatesbooststatechart

Boost statechart - compilation error when using state chart as template parameter


I'm trying to implement a simple state machine using boost statechart. Since I have several variation of this state machine, I thought it might be a good idea to wrap it in a template and pass the state machine as template parameter.

However, I'm getting compilation errors.

Code:

#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/transition.hpp>

namespace sc = boost::statechart;


class ComponentType
{
};

class FSM {
protected:
  struct stInit ;     
public:
  struct Machine : sc::state_machine< Machine, stInit > {};
protected:

  struct stInit : ComponentType, sc::simple_state< stInit, Machine >  {};
};

template <class fsm>
void run() {
  typename fsm::Machine m_fsm;
  const ComponentType &t = m_fsm.state_cast<const ComponentType &>();
  (void) t;
}

int main() {
  run<FSM>();
}

The compilation errors:

fsmtest.cpp: In function ‘void run()’:
fsmtest.cpp:33:45: error: expected primary-expression before ‘const’
   const ComponentType &t = m_fsm.state_cast<const ComponentType &>();
                                             ^
fsmtest.cpp:33:45: error: expected ‘,’ or ‘;’ before ‘const’

However, when using typedef instead of template:

typedef FSM fsm;
//template <class fsm>

and

  run();
  //  run<FSM>();

Everything compiles without any errors.

What am I missing?

(compiler: g++ 4.8.4, OS: Ubuntu 14.04, boost: 1.54)


Solution

  • You have to let compiler know that you want to call state_cast template function, so it would parse the line correctly. Change:

    const ComponentType &t = m_fsm.state_cast<const ComponentType &>();
    

    to:

    const ComponentType &t = m_fsm.template state_cast<const ComponentType &>();
    

    Check Where and why do I have to put the "template" and "typename" keywords? for more info.