0

I would like to mulitply a matrix with 3 elements (like a vector from physics) double3 with a scalar value. I wrote a class for everything (as you can see below). The problem is, that the overloaded operator* is not recognized. I can't find any issues with the syntax and also tried to adding const and & accordingly, to make sure the operator accept rvalues too.

Error   C2676   binary '*': 'double3' does not define this operator or a conversion to a type acceptable to the predefined operator

Can anyone tell me where the issue is in the following code is?

// main
#include "vec3.h"

int main() {
    double3 result, result2;
    double3 vec = { 1,2,3 };
    double testd = 2.3;
    result = vec * testd;
    result2 = vec * (testd / 5.0);
}
// vec3.h
#pragma once
#include <iostream>

template <typename T>
struct vec3 {
    // assign data
    vec3(const T u, const T v, const T w) : d{ u,v,w } {}
    vec3(const T a[3]) : d{ a[0],a[1],a[2] } {}
    vec3() : d{ 0,0,0 } {}
    
    // read (and write) data
    T& operator[] (int i) { return d[i]; }
    T operator() (int i) const { return d[i]; }

    // vec3.cpp contains more mathematical operations

protected:
    T d[3];
};

using double3 = vec3<double>;
using int3 = vec3<int>;
// vec3.cpp
#include "vec3.h"

// vec3-scalar operations
template<typename T>    // scalar multiplication
vec3<T> operator*(const vec3<T>& a, T s) {
    return vec3<T>(a(0) * s, a(1) * s, a(2) * s);
}
template<typename T>    // scalar multiplication 2
vec3<T> operator*(T s, const vec3<T> &a) {
    return vec3<T>(a(0) * s, a(1) * s, a(2) * s);
}
Silas
  • 1
  • 4
  • 1
    what file is the third block of code in ? – Jeffrey Jan 28 '21 at 18:45
  • The issue is that all template code, including overloads, must be defined and `#include`d in header files. – Sam Varshavchik Jan 28 '21 at 18:47
  • @SamVarshavchik I think that solves the issue (and might even solve a previous isse I had with the linker ([link](https://stackoverflow.com/questions/65902704/linking-error-lnk2019-unresolved-external-symbol-without-external-libraries)), but that's not tested yet). Is it better to `#include "vec3.cpp"` in the main oder vec3.h file? – Silas Jan 28 '21 at 18:53
  • @Silas No it's better to delete vec.cpp and put all its contents into vec.h. Template code must be in header files, don't pretend it can be anywhere else. – john Jan 28 '21 at 19:03
  • Ok, sorry, I'm still rather new and thought most code should go into the .cpp files. – Silas Jan 28 '21 at 19:05
  • The name of a file is irrelevant. It can be `.cpp`, `.h`, .`.snorkle`, or even `.awesome`. A C++ compiler doesn't care what's the name of the file it is compiling, it results in absolutely no difference whatsoever. The only thing that matters is that the C++ compiler knows it contains C++ code, and not something else. – Sam Varshavchik Jan 28 '21 at 19:09

0 Answers0