0

Trying to understand sample from wikipedia

template <int length>
Vector<length>& Vector<length>::operator+=(const Vector<length>& rhs) 
{
    for (int i = 0; i < length; ++i)
        value[i] += rhs.value[i];
    return *this;
}

template <>
Vector<2>& Vector<2>::operator+=(const Vector<2>& rhs) 
{
    value[0] += rhs.value[0];
    value[1] += rhs.value[1];
    return *this;
}

Firsttly I can't compile it at all. I got error syntax error : missing ';' before '<'

And second question is how to use it? As far as I understand template name Vector is not the same like std::vector.

1
  • 1
    this is just part of a Vector class. it cannot be compiled alone. and you'll also need calling code to test it. Oct 13, 2014 at 8:52

2 Answers 2

4

This is just (a small) part of a Vector class, showing a concept for teaching purposes.

It cannot be compiled alone. You'll have to write the rest of the class.

Then you'll have to write calling code which instantiates the template and calls the operators to test it. Then debug it (or add trace messages) to show that the right overload is resolved.

Note also that it says "the following code may be produced". You don't actually need the second code. It just shows what an optimizer compiler can do with your code.

-3

Try defining the class like:

template <int length>
class Vector
{
    Vector<length>& operator+=(const Vector<length>& rhs);
    Vector<2>& operator+=(const Vector<2>& rhs);
};

I would recommend going for an online C++ tutorial

4
  • My first answer, which is a good and working answer, I don't understand the vote downs, if I was wrong I would understand.
    – shlomoa
    Oct 13, 2014 at 11:42
  • (Not my vote) The <2> bit doesn't do what you think it should do, nor is it related to the Wikipedia example.
    – MSalters
    Oct 13, 2014 at 11:54
  • Right, but 1) it is correct 2) it matches the code.
    – shlomoa
    Oct 13, 2014 at 13:24
  • 1
    No, you define template <int len> Vector<2>& Vector<len>::operator+=(const Vector<2>& rhs) - note the inconsistent template arguments. In particular, return *this won't work for len!=2.
    – MSalters
    Oct 13, 2014 at 14:02

Your Answer

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

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