I am making a dependency injection system via static polymorphism with C++20 concepts, so I have this example
I have an interface contract for a Logger:
template <typename TLogger>
concept ILogger = requires(TLogger engine) {
{ engine.LogInfo(std::declval<std::string>()) } -> std::same_as<void>;
{ engine.LogError(std::declval<int>(), std::declval<std::string>()) } -> std::same_as<void>;
};
A particular implementation of that interface with 2 ctors, a default and a non-default:
class MyLoggerImplementation
{
public:
MyLoggerImplementation() : x(0)
{
}
MyLoggerImplementation(int code) //non default constructor
{
x = code;
}
//Interface methods
public:
void LogInfo(std::string errorMessage)
{
std::cout << std::format("Info: {}!\n", errorMessage);
}
void LogError(int errorCode, std::string errorMessage)
{
std::cout << std::format("Error: {}! with code: {}\n", errorMessage, errorCode);
}
// private members
private:
int x;
};
Then my DatabaseAccessor has a dependency to a Logger:
template<ILogger Logger>
class DatabaseAccessor
{
public:
DatabaseAccessor() { }
public:
bool QueryAll()
{
logger.LogInfo("querying all data");
//...
return true;
}
// Injected services
private:
Logger logger;
};
And then when I try to instantiate a DatabaseAccessor and I inject the Logger dependency with MyLoggerImplementation it will call the default constructor:
int main()
{
DatabaseAccessor<MyLoggerImplementation> db; // this will instantiate with the default constructor
// DatabaseAccessor<MyLoggerImplementation(10)> db; // ???
db.QueryAll();
}
How can I instantiate MyLoggerImplementation with that non-default constructor?