Let's say I have a C++ class (class A) which needs to have references to variable number of instances of another class (class B). The needed number of references is known at compile time. As far as the usage I would like to have the ability to pass the references to the B type objects to the A type object at compile time.
I have been thinking about how to solve that problem and one idea which I have is to use variadic template construct. I am not very familiar with variadic templates so before studying that topic I would like to know whether it is good solution for my problem.
The references should probably be (smart) pointers or std::ref
objects. I use regular pointers for brevity. Depending on how exactly you want to pass them to the constructor, you can do this:
template <std::size_t nobj> class A
{
std::array<B*, nobj> bs;
public:
// 1 Pass as separate arguments
template <typename ... T>
A(T* ... t) : bs{t...} {
// check that the number of arguments is ok
static_assert(nobj == sizeof ...(T));
}
// 2 Pass as an array
A(const std::array<B*, nobj>& bs) : bs(bs) {}
};
// deduce the template parameter from the number of arguments
template<typename ... T>
A(T... t) -> A<sizeof ... (T)>;
so you can do initialisation both like this:
A a{&b1, &b2, &b3};
and like this:
std::array<B, 3> bs{&b1, &b2, &b3};
A a(bs);