Sivaram
Sivaram

Reputation: 155

Build a compile time command look up table using template metaprogramming

I am trying to build a command parser for a embedded system(bare metal) where it will receive command via message and call corresponding function. The structure will look like

struct cmdparse{
    char* commandname;
    function_pointer;
};

Initially the respective modules will register the command they will serve and the corresponding function pointer. The command parser builds the look up table during initialisation. when ever a command is received it parses the table and calls the corresponding function, Is it possible to achieve this i.e build this look up table in compile time using template metaprogramming. The main advantage I am expecting is when ever a new command is added, I don't need to check the command parser to see if the array size needs to be increased. Since it is a embedded system project usage of vector is banned due to dynamic memory requirements. Plus if this look up table goes to ROM instead of RAM it will add a safety clause of avoiding un intentional corruption.

Upvotes: 3

Views: 153

Answers (1)

darune
darune

Reputation: 10982

If you have decent compiler (enable at least ) you can build at compile-time with:

struct cmdparse{
    const char* commandname;
    void (*fn)();
};

void whatever1();
void whatever2();

constexpr cmdparse commands[] = {//<--compiler time
  cmdparse{"cmd1", &whatever1}, 
  cmdparse{"cmd2", &whatever2}
};

If you don't have a good compiler you may need to remove - but otherwise this method should work.


Making room for more commands at runtime is perhaps best done in a seperate array:

std::array<cmdparse, 1024> dyn_commands; //<-- supports up to 1024 commands

Upvotes: 5

Related Questions