M4st3rM1nd
M4st3rM1nd

Reputation: 217

Template operator overload in source file instead of header

I made a simple Vector2 Template class which I use to store an X and an Y value. Now I'm trying to keep implementation of templates in the source files, but I fail to do this with operator overloading

    class Vector2
    {
    public:
        Vector2<Type>();
        Vector2<Type>(Type x, Type y);
        Vector2<Type>(const Vector2<Type> &v);
        ~Vector2<Type>();
        Vector2<Type> operator+ (const Vector2<Type> &other)
        {
            return Vector2<Type>(x + other.x, y + other.y);
        }
    private:
        Type x, y;
    };

Now this compiles and works just fine but this is currently located in the header file. Implementing the constructor and de-constructor of Vector2 works perfectly fine aswell but when I try the following:

.h:

    Vector2<Type> operator+ (const Vector2<Type> &other);

.cpp:

    template <class Type>
    Vector2<Type>::operator+ (const Vector2<Type> &other)
    {
        return Vector2<Type>(x + other.x, y + other.y);
    }

the compiler tells me: missing type specifier - int assumed. Note C++ does not support default-int

Kind regards, Me

Upvotes: 3

Views: 2637

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126522

Your definition of operator + is missing a return type:

    template <class Type>
    Vector2<Type> Vector2<Type>::operator+ (const Vector2<Type> &other)
//  ^^^^^^^^^^^^^
    {
        return Vector2<Type>(x + other.x, y + other.y);
    }

Also notice, that the definitions of a class template's member functions should appear in the same header that contains the class template definition, unless you are using explicit instantiations for all the instantiations that would otherwise be created implicitly (see this Q&A on StackOverflow).

Upvotes: 4

Related Questions