Idiomatic way to implement capability discovery on include in C++

6 hours ago 2
ARTICLE AD BOX

Twice now I've come up against a desire to add some capability in an included C++ file to some global list of capabilities, and I'm wondering what the best way to do it is.

The two use cases I have are:

I'd like to define a bunch of tests across a bunch of files, and then in test.cpp do something like the following:

#include "module1/test.h" #include "module2/test.h" #include "test.h" int main() { for (const auto& test : autodiscover()) { // or `for (const auto& test : TESTS)` test(); } }

(With error reporting and whatever other information).

I have a project that is a bunch of different executables which one can imagine as microservices (even though they're not quite), which all operate on the same database in some measure or other. For reasons I won't go into here, each statement that is executed on the database is PREPAREd ahead of time, at executable startup. This is done with a repo::init() function.

As it currently stands, that function has a statically defined array of all prepareSomething()s, and calls them in turn.

This is unfortunate because it means I can't split up the repository to multiple translation units, which I would like to do. I think it would be nice if updating updateCustomerEmail() didn't cause a recompilation of the monthly-earnings-report executable, even though the latter never calls the former, for example.

To that end, I would like each fragment of the repository to add its prepareXYZ()s to a global list of "things to init", so when the main executable calls repo::init(), all of the statements that executable can execute are prepared, and nothing else is prepared.

---

I feel like what I want to do is possible, and possibly easily so, because everything is available at compile time, but I can't find a way there. All my googling is doing is leading me to service discovery, and telling me to use a network layer which is obviously not the problem I'm trying to solve.

Read Entire Article