Skip to content

Instantly share code, notes, and snippets.

@nthery
Created September 24, 2023 17:58
Show Gist options
  • Save nthery/46ff90965392defc86a962c569648b7f to your computer and use it in GitHub Desktop.
Save nthery/46ff90965392defc86a962c569648b7f to your computer and use it in GitHub Desktop.
Ben Deane's global dependency injection pattern
// Ben Deane's global dependency injection pattern.
// https://www.youtube.com/watch?v=BYpcAEfG3mo
#include <utility>
//
// Header providing service and its default implementation.
//
struct default_logger {
template<class ...Args>
void log(Args&&...);
};
// Template so it can be overriden by specialization.
template<class...>
inline auto injectable_logger = default_logger();
// API
template<class ...DummyArgs, class ...Args>
void log(Args&&... args) {
// DummArgs are just there to allow specialization.
static_assert(sizeof...(DummyArgs) == 0);
auto interface = injectable_logger<DummyArgs...>;
interface.log(std::forward<Args>(args)...);
}
//
// Header providing alternative implementation
//
struct test_logger {
template<class ...Args>
void log(Args&&...);
};
// If the following line is commented out, main() will call the
// default implementation.
template<> inline auto injectable_logger<> = test_logger();
//
// Client
//
int main() {
log(1, "2", 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment