I intend to implement the multiplication operator of my "Sparse Vector" and "Vector" classes. The following simplified code demo shows my problem
The Vector class in Vector.hpp
#pragma once
template <typename T>
class Vector
{
public:
Vector() {}
template <typename Scalar>
friend Vector operator*(const Scalar &a, const Vector &rhs) // #1
{
return Vector();
}
};
The Sparse Vector class in SpVec.hpp
#pragma once
#include "Vector.hpp"
template <typename T>
class SpVec
{
public:
SpVec() {}
template <typename U>
inline friend double operator*(const SpVec &spv, const Vector<U> &v) // #2
{
return 0.0;
}
};
The test code in main.cpp:
#include "Vector.hpp"
#include "SpVec.hpp"
#include <iostream>
int main()
{
Vector<double> v;
SpVec<double> spv;
std::cout << spv * v;
return 0;
}
I build the test program with
g++ main.cpp -o test
which gives the ambiguous template deduction error
main.cpp: In function ‘int main()’:
main.cpp:13:26: error: ambiguous overload for ‘operator*’ (operand types are ‘SpVec<double>’ and ‘Vector<double>’)
std::cout << spv * v;
~~~~^~~
In file included from main.cpp:2:0:
SpVec.hpp:12:26: note: candidate: double operator*(const SpVec<T>&, const Vector<U>&) [with U = double; T = double]
inline friend double operator*(const SpVec &spv, const Vector<U> &v) // #2
^~~~~~~~
In file included from main.cpp:1:0:
Vector.hpp:10:19: note: candidate: Vector<T> operator*(const Scalar&, const Vector<T>&) [with Scalar = SpVec<double>; T = double]
friend Vector operator*(const Scalar &a, const Vector &rhs) // #1
I expect the #2
method definition is more close to my calling.
Please help me understand how the ambiguous error comes out and how to resolve the issue.