【发布时间】:2018-11-13 05:58:32
【问题描述】:
我打算实现我的“稀疏向量”和“向量”类的乘法运算符。下面的简化代码演示显示了我的问题
Vector.hpp
中的Vector类#pragma once
template <typename T>
class Vector
{
public:
Vector() {}
template <typename Scalar>
friend Vector operator*(const Scalar &a, const Vector &rhs) // #1
{
return Vector();
}
};
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;
}
};
main.cpp中的测试代码:
#include "Vector.hpp"
#include "SpVec.hpp"
#include <iostream>
int main()
{
Vector<double> v;
SpVec<double> spv;
std::cout << spv * v;
return 0;
}
我用
构建测试程序g++ main.cpp -o test
这给出了模棱两可的模板推导错误
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
我希望#2 方法定义更接近我的要求。
请帮助我了解模棱两可的错误是如何产生的以及如何解决问题。
【问题讨论】:
标签: c++ templates metaprogramming ambiguous