ARTICLE AD BOX
I have a list of callbacks to invoke whenever some event happens and I would like to allow subscribing to it without having to explicitly call the subscribing function:
// subscription.h #include <function> #include <vector> class subscription { public: void add(std::function<void()> fun) { funs.emplace_back(std::move(fun)); } void execute() { for (const auto& fun : funs) { fun(); } } private: static inline auto funs = std::vector<std::function<void()>>{}; }; // main.cpp #include "subscription.h" int main() { // optional API to execute all additions, if needed // subscription.gather(); subscription.execute(); } // hello.cpp #include "subscription.h" #include <iostream> void subscribe_hello() { subscription.add([](){ std::cout << "Hello World!\n"; }); } // Will this work? static int dummy_hello = [](){ return subscribe_hello(), 1; }();I know most reliable way would be to have main() just call subscribe_hello(), but I don't want to edit some common code every time I add a new callback. I also know it would work if some code used dummy_hello, since it would force static initialization via IIFE, but again I don't want to do that. So this will work similar to gtest, where you only need to declare a test, and it gets automatically registered.
So will the static object be initialized even if it is not used? What if I add constexpr or constinit? If it works, do I have to worry about any thread safety? If it does not work, is there any way to achieve invocation of a function at program entry from arbitrary translation unit?
