Skip to content

Instantly share code, notes, and snippets.

@wotchin
Created May 30, 2023 02:27
Show Gist options
  • Save wotchin/95c00577119acfc96e416b895ac546c2 to your computer and use it in GitHub Desktop.
Save wotchin/95c00577119acfc96e416b895ac546c2 to your computer and use it in GitHub Desktop.
C++: Self-registering functions using macros for test libraries
// ---- .hpp ----
// Refer to
// https://blog.rubenwardy.com/2019/02/17/cpp-self-registering-test-macros
#include <functional>
#define Test(name) \
void test_##name(); \
static bool test_##name##_registered = TestFactory::Register(#name, &test_##name); \
void test_##name()
class TestFactory {
public:
static bool Register(std::string name, std::function<bool()> func);
private:
static std::map<std::string, std::function<bool()>> Tests;
}
// ---- .cpp ----
std::map<std::string, std::function<bool()>> TestRunner::Tests;
bool TestFactory::Register(std::string name, std::function<bool()> func) {
auto it = Tests.find(name);
if (it == Tests.end()) {
Tests[name] = std::move(func);
return true;
}
return false;
}
@wotchin
Copy link
Author

wotchin commented May 30, 2023

Another pretty static registration macro refers to
https://artificial-mind.net/blog/2020/10/17/static-registration-macro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment