Reputation: 113
I have the following templated classes MyObject
and SmallObject
. Below, I have a constructor for a MyObject
that takes a vector as input and converts each item in the vector into a SmallObject
. However, when it runs in tests, it returns an error for no matching constructor.
I can't tell what is wrong, my guess was that somehow the values I'm pulling from the vector are not of type T, but I don't understand how this could be the case. This is also a simplified snippet of the relevant parts so don't worry about the fact it's not doing anything with the SmallObj and leaking memory
template<typename T>
SmallObj<T>::SmallObj(T& value) : _value(value) {}
template<typename T>
MyObject<T>::MyObject(const std::vector<T>& values) {
int n = values.size();
for (int i = 0; i < n; i++) {
SmallObject<T>* node = new SmallObject<T>(values[i]); // error: no matching constructor
}
}
Upvotes: 1
Views: 38
Reputation: 172964
The parameter values
is passed as reference to const
, then values[i]
returns const T&
. While the constructor of SmallObj
takes reference to non-const which can't bind to constant. If it's not supposed to modify the argument you can change the constructor to take reference to const
.
template<typename T>
SmallObj<T>::SmallObj(const T& value) : _value(value) {}
Upvotes: 1