Reputation: 1123
I have a code that creates the objects. Each object can consist of any number of modules and optionally a configuration. To cover both cases I had to create two methods (below is a "scenario" code).
template <typename Impl, typename ... Modules>
Impl create(Ioc& ioc)
{
return Impl{ioc.create<Modules>()...};
}
Too add optional configuration, another version has to be written
template <typename Impl, typename Config, typename ... Modules>
Impl create(Ioc& ioc, const Config& config)
{
return Impl{ioc.create<Modules>()..., config};
}
Is it possible to somehow create one method that would cover both cases?
Upvotes: 0
Views: 61
Reputation: 7184
You can use multiple parameter packs if you put the Config last:
template <typename Impl, typename... Modules, typename... Config>
Impl create(Ioc& ioc, Config const& ... config) {
return Impl{ioc.create<Modules>()..., config ...};
}
You can also split the parameter packs using a lambda:
template <typename Impl, typename ... Modules>
auto create = [](Ioc& ioc, auto const& ... config) -> Impl {
return Impl{ioc.create<Modules>()..., config ...};
};
This will accept any number of parameters after the first Config
. To enforce only zero on one extra arguments, add
static_assert(sizeof...(config) <= 1);
Upvotes: 2