Search code examples
c++templatesoperator-overloadingfriend

C++ template class friend operator overloading


I'm trying to make a universal vector class, both for the sake of my own snippet library and to practice with templated classes. Essentially, the Vector class is templated to allow you to chose whether its precision is float, double, long double, etc.

The issue I've run into is with overloading the * operator for the purpose of scaling the vector. With all working overloads and member functions excluded, the class definition looks like this:

#pragma once

#include <math.h>   //  for sqrt function when normalizing

template <typename T> class Vector;
template <typename T> Vector<T> operator*(const Vector<T>& obj);

template <typename T> class Vector {
private:
    //  Attributes:
    static const int DIMS = 3;
    T component[DIMS];

public:
    enum { 
        X, Y, Z
    };

public:
    //  Constructors:
    Vector(void) {
        for (int i=0; i<DIMS; ++i) {
            component[i] = T();
        }
    }
    Vector(T x, T y, T z) {
        component[X] = x;
        component[Y] = y;
        component[Z] = z;
    }

    //  Destructor:
    ~Vector(void) { }

    //  Scaling:
    friend Vector<T> operator*(const Vector<T>& obj);
    Vector operator*(const T scale) {
        Vector<T> result = Vector<T>();

        for (int i=0; i<DIMS; ++i) {
            result.component[i] = component[i] * scale;
        }

        return result;
    }
};

template <typename T>
Vector<T> operator*(const Vector<T>& obj) {
    Vector<T> result = Vector<T>();

    for (int i=0; i<DIMS; ++i) {
        result.component[i] = obj.component[i] * this*;
    }

    return result;
}

In my main method, I have the following lines of code:

Vector<float> testVector1 = Vector<float>(1.0f, 0.0f, 0.0f);
Vector<float> testVector2 = Vector<float>(0.0f, 1.0f, 0.0f);
Vector<float> testVector3 = 10.0f * testVector1;
Vector<float> testVector4 = testVector2 * 10.0f;

Everything compiles fine except for one error: While the fourth line in main() works fine (multiplying the vector by a scalar) the third (multiplying a scalar into the vector) gives me the error:

Error 1 error C2677: binary '*' : no global operator found which takes type 'Vector<T>' (or there is no acceptable conversion)

My best guess on the issue is that the compiler doesn't know which primitive's * operator I'm trying to overload, and I can't directly tell it since the class won't know the type until it's passed into the template. Is there a way to accomplish what I'm trying to do, or must the template always follow the class for operator overloading?

Update: So I caught the bad attempt at a left-handed overload thanks to jwismar and others. The definition for the function within the class is now:

friend Vector<T> operator*(T scalar, const Vector<T>& obj);

And it's implementation is:

template <typename T> 
Vector<T> operator*(T scalar, const Vector<T>& obj) {
    Vector<T> result = Vector<T>();

    for (int i=0; i<DIMS; ++i) {
        result.component[i] = obj.component[i] * scalar;
    }

    return result;
}

The initial declaration of the overload above the class is now template <typename T> Vector<T> operator*(T scalar, const Vector<T>& obj);, but I get the same error regardless of whether it's commented out or not.

Now I'm on to a more specific question regarding templates and operator overloading. The compiler now balks at compile, though the error is now an unresolved external:

Error 1 error LNK2019: unresolved external symbol "class Vector<float> __cdecl operator*(float,class Vector<float> const &)" (??D@YA?AV?$Vector@M@@MABV0@@Z) referenced in function _main C:\Users\D03457489\Desktop\UVCTester\UVCTester\main.obj UVCTester

So the compiler is telling me it can find a definition for operator*(float, Vector<float>) but can't find the implementation. So the new question is: is that the result of another basic oversight on my part, or is it just not possible to use templates in this way to generate operator overloads where the left side of the operand is unknown?


Solution

  • Try this function signature instead (not tested):

    template <typename T, typename F>
    Vector<T> operator*(const F &lhs, const Vector<T>& rhs);
    

    It should allow for statements like:

    auto vec = f * other_vec;
    

    for any type F which has a defined operator of the kind:

    template <typename F, typename T>
    undetermined operator*(const F& lhs, const T &rhs);
    

    where T is the type used for the Vector<T>, and the returned type can implicitly cast to T.

    So the following would probably work:

    long l;
    float f;
    int i;
    //.......
    
    Vector<float> v1;
    v2 = l * v1;
    v3 = f * v2;
    v4 = i * v3;