Recently I asked this question but now I would like to expand it. I wrote the following class:
template <class T>
class X{
public:
vector<T> v;
template <class T>
X(T n) {
v.push_back(n);
}
template <class T, class... T2>
X(T n, T2... rest) {
v.push_back(n);
X(rest...);
}
};
When creating an object using
X<int> obj(1, 2, 3); // obj.v containts only 1
Vector only contains the first value, but not others. I've checked and saw that constructor is called 3 times, so I'm probably creating temp objects and filling their vectors with the rest of the arguments. How do I solve this problem?
First, your code doesn't compile for me.
main.cpp:7:15: error: declaration of ‘class T’
template <class T>
^
main.cpp:3:11: error: shadows template parm ‘class T’
template <class T>
^
I changed the outer one to U
.
template <class U>
class X{
public:
vector<U> v;
template <class T>
X(T n) {
v.push_back(n);
}
template <class T, class... T2>
X(T n, T2... rest) {
v.push_back(n);
X(rest...);
}
};
You're correct that this causes the issue you gave in the question details...
X<int> obj(1, 2, 3); // obj.v containts only 1
This is because the statement X(rest...)
at the end of your constructor doesn't recursively call the constructor to continue initializing the same object; it creates a new X
object and then throws it away. Once a constructor's body begins to execute, it's no longer possible to invoke another constructor on the same object. Delegation must occur in the ctor-initializer. So for example, you could do this:
template <class T, class... T2>
X(T n, T2... rest): X(rest...) {
v.insert(v.begin(), n);
}
That sucks though, because inserting at the beginning of a vector isn't efficient.
Better to take a std::initializer_list<T>
argument. This is what std::vector
itself does.
X(std::initializer_list<U> il): v(il) {}
// ...
X<int> obj {1, 2, 3};