Created
May 30, 2023 02:27
-
-
Save wotchin/95c00577119acfc96e416b895ac546c2 to your computer and use it in GitHub Desktop.
C++: Self-registering functions using macros for test libraries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- .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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another pretty static registration macro refers to
https://artificial-mind.net/blog/2020/10/17/static-registration-macro
.