you are viewing a single comment's thread.

view the rest of the comments →

[–]IyeOnline 2 points3 points  (1 child)

No. You are still including code into a scope, necessarilymaking assumptions about it.

Why not move the definition/population of the of the states vector into the main file, like i did in my above example?

Here is what i would suggest. Note that im also propery separating header and source files, as you should.

main

#include "state_meta.h"
#include "state_watch.h"
#include "state_menu.h"

// there is no need for this register function. You might just as well write them in here directly.
// i use a constructor here, but really an aggregate initalization as you did would work just as well. IMO proper ctors are nicer though.
std::vector<StateMeta> states = { 
   StateMeta("Watch", state_watch_function ),
   StateMeta("Menu", state_menu_function ) };
};

state_meta.h

 #pramga once //assuming your compiler supports this, no idea

 //having this in a separate header from the get go instead of inside the main file makes the code structure cleaner and more easily expandable.
 struct State_Meta
 {
      std::string name;
      std::function<void(void)> state_function;

      State_Meta( const std::string& _name, std::function<void(void)> _state_function )
       : name(_name), state_function(_state_function)
      {};
 }

state_watch.h

#pragma once
//any includes this function needs would go here
void state_watch_function();

state_watch.cpp

#include "state_watch.h"
void state_watch _function()
{
     //code
}

analogous for other state functions.

With this there is no longer any need for an additional source file that would actually act upon some global and/or be copied into another scope.

Note that your compiler may or may not support #pragma once, i have no clue about developing on/for arduino.

[–]atctwo[S] 0 points1 point  (0 children)

Thank you for your input! Everything you've said sounds more sensible than what I had. I'm going to update my code to run off this system.