c++ - Queuing a call in headers -
the goal allow header files "register" initializer function main can iterate on functions , call them. i've stumbled upon solution uses __attribute__
, seems gcc-only (https://stackoverflow.com/a/37082249/7867841).
// header1.h void myinitializer(){} register_this(&myinitializer); // header2.h void myinitializer2(){} register_this(&myinitializer2); // main.cpp ... for_each_registered_ptr(){ call_ptr(); } // calls myinitializer , myinitializer2 ...
is there universal solution this? functions can switched classes or types if that's easier implement.
you can abuse static
function locals this, avoiding static initialization order fiasco.
in init.h
, have this:
#ifndef init_h #define init_h #include <vector> // can changed std::function<...> or whatever need. typedef void (*init_fn)(); // returns int can used in variable initializer. int register_initializer(init_fn fn); std::vector<init_fn> & get_initializers(); #endif
then, in init.cpp
:
#include "init.h" int register_initializer(init_fn fn) { get_initializers().push_back(fn); return 0; } std::vector<init_fn> & get_initializers() { static std::vector<init_fn> ip; return ip; }
a few notes, before move on rest:
- the
static
local initialized once, first time function called. - the "global" vector kind-of-leaked. it's unlikely problem unless adding tens of thousands of entries vector. can
get_initializers().clear()
empty out after using it.
we'd use so, in a.cpp
:
#include <iostream> #include "init.h" static void a_init() { std::cout << "a_init()\n"; } static auto dummy = register_initializer(a_init);
and, finally, have our (rather simple) main.cpp
:
#include "init.h" int main() { (auto fn : get_initializers()) { fn(); } return 0; }
Comments
Post a Comment