Reputation: 327
I have a C++ template class (in Qt) that should handle a list of custom items. This class has a simple member function that is supposed to call the constructor of the template type and add the created item to the list.
void CustomList::addElement(void)
{
T *element = new T();
// ...
}
But I have a problem : I'd like this function to be able to call overloaded constructors.
I thought I could give it the arguments that should be used in the constructor. So it would be called with as arguments a "copy" of the arguments given to addElement().
Except that I don't know how many of them there are, no more than their types. Any simple way I could do it ?
Upvotes: 2
Views: 158
Reputation: 60979
So it would be called with as arguments a "copy" of the arguments given to addElement().
Why copies when you can use the original arguments?
With C++11 you can use variadic templates and perfect forwarding:
template <typename... Args>
void CustomList::addElement(Args&&... args)
{
T *element = new T(std::forward<Args>(args)...);
// ...
}
Without proper C++11 support you will have to overload the addElement
function (template) for every amount of arguments until a sensible limit is reached. I.e.
template <typename Arg1>
void CustomList::addElement(Arg1 const& arg1)
{
T *element = new T(arg1);
// ...
}
template <typename Arg1, typename Arg2>
void CustomList::addElement(Arg1 const& arg1, Arg2 const& arg2)
{
T *element = new T(arg1, arg2);
// ...
}
// [...]
Upvotes: 5