1

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
  }
}
3
  • 1
    Just a wild, wild guess, but SmallObject may not be the same thing as SmallObj? Nov 3, 2020 at 3:34
  • 1
    values[i] will be a const T& but the constructor accepts T&.
    – jtbandes
    Nov 3, 2020 at 3:35
  • @SamVarshavchik ahh oops that was just a problem with me writing up the question, thank you for catching that Nov 3, 2020 at 3:43

1 Answer 1

1

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) {}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.