Is there a tidy way of associating metadata with functions in C++ -
i have codebase many command line options. currently, each command line option lives in table along function pointer run if command passed in on command line.
e.g.
static commandfunction s_commands[] = { { "command1", func1 }, { "command2", func2 }, { "command3", func3 }, etc... };
my problem is, table huge, , functions live elsewhere. prefer string command live right beside each function.
so example:
command_arg("command1") void func1() { dostuff ... } command_arg("command2") void func2() { dostuff ... } command_arg("command3") void func3() { dostuff ... }
is possible?
you can template specialized address of function:
#include <stdio.h> // in header file. template<void(*fn)()> struct fnmeta { static char const* const meta; }; // no definition of meta // some.cc void some() {} template<> char const* const fnmeta<some>::meta = "some"; // another.cc void another() {} template<> char const* const fnmeta<another>::meta = "another"; // main.cc int main() { printf("%s\n", fnmeta<some>::meta); printf("%s\n", fnmeta<another>::meta); }
the idea above fnmeta<>::meta
not defined. however, different translation units (.cc files) can provide definition of specialization of fnmeta<>::meta
. way when fnmeta<x>::meta
used linker finds appropriate definition of in translation unit.
Comments
Post a Comment