0

I am making program in which I create class for vector and overload different operators. Now I want to make arguments of vector (coordinates) as templates. When I have all code in one file everything is alright and program is running correctly:

#ifndef VECTOR4D_H_INCLUDED
#define VECTOR4D_H_INCLUDED
template <typename TYPE>
class VECTOR4D{
    public:
       VECTOR4D (void): X(0), Y(0), Z(0), T(0){};
       VECTOR4D (TYPE X, TYPE Y, TYPE Z, TYPE T): X(X), Y(Y), Z(Z), T(T){};
       TYPE X, Y, Z, T;

       VECTOR4D &operator+=(VECTOR4D &K){
           this->X += K.X;
           this->Y += K.Y;
           this->Z += K.Z;
           this->T += K.T;

           return *this;
       }
};


#endif // VECTOR4D_H_INCLUDED

but when I separate implementation and declaration of overload operator I have a problem.

//vector4d.h
#ifndef VECTOR4D_H_INCLUDED
#define VECTOR4D_H_INCLUDED
template <typename TYPE>
class VECTOR4D{
    public:
        VECTOR4D (void): X(0), Y(0), Z(0), T(0){};
        VECTOR4D (TYPE X, TYPE Y, TYPE Z, TYPE T): X(X), Y(Y), Z(Z), T(T){};
        TYPE X, Y, Z, T;

        VECTOR4D &operator+=(VECTOR4D &);
};


#endif // VEKTOR4D_H_INCLUDED

//project.cpp
#include <iostream>
#include "vector4d.h"

VECTOR4D &VECTOR4D::operator+=(VECTOR4D &K)
{
    this->X += K.X;
    this->Y += K.Y;
    this->Z += K.Z;
    this->T += K.T;

    return *this;
}

During compilation i have got an error:

invalid use of template-name 'VECTOR4D' without an argument list

How I have to do this to make it correct?

Szamot
  • 366
  • 2
  • 12
  • Sorry, I know the dupe isn't perfect, but I feel it's almost there. In order to define a member of a class template, the definition must also be a template: `template VECTOR4D &VECTOR4D::operator+=(VECTOR4D &K) {...}`. Note that `K` should really be a const reference since nothing is changed. You're preventing the caller from passing in perfectly reasonable arguments. – chris Apr 10 '15 at 23:25

1 Answers1

0

VECTOR4D is a template class. All methods of template class must be implemented in header file (you can read here about it here: Why can templates only be implemented in the header file? )

You also should specify template parameter if you define template class method outside class declaration

template<typename TYPE>
VECTOR4D<TYPE> &VECTOR4D<TYPE>::operator+=(VECTOR4D<TYPE> &K)
{
    this->X += K.X;
    this->Y += K.Y;
    this->Z += K.Z;
    this->T += K.T;

    return *this;
}
Community
  • 1
  • 1
Sandro
  • 2,707
  • 2
  • 20
  • 30