我想编写一个自己的Vector类和一个计算叉积的函数。
我的Vector-class有
template<class T, int dim, bool isRowVector>
T是条目的类型,dim维度,isRowVector指定向量是行向量还是列向量。
我重载了Vector的一些运算符,特别是&lt;&lt;&lt;:
template <class T, int dim, bool isRowVec>
std::ostream& operator<<(std::ostream& os, Vector<T, dim, isRowVec>& vec) // <<
{
os << "[" << vec[0];
for(typename std::vector<T>::iterator it = vec.begin()+1; it != vec.end(); it++) {
os << "," << *it;
}
os << "]";
if(!isRowVec) { os << "^T"; }
return os;
}
现在函数crossProduct只应用于dim = 3的Vectors。所以我指定了这样的函数:
template <class T, bool isRowVec>
Vector<T, 3, isRowVec> crossProduct (Vector<T, 3, isRowVec> a, Vector<T, 3, isRowVec> b) {
T arr[3] = { a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0] };
Vector<T, 3, isRowVec> newVec(arr);
return newVec;
}
省略函数模板中的dim参数,因为它不必被猜测或说明。
这似乎不是问题,因为
Vector<float,3,true> a = crossProduct(f,g);
不会产生编译错误,其中f和g都是
Vector<float,3,true>
但是当我试着打电话时
std::cout << crossProduct(f, g) << std::endl;
我得到了
error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Vector<float, 3, true>')
std::cout << crossProduct(f, g) << std::endl;
^
有什么想法吗?
答案 0 :(得分:2)
std::cout << crossProduct(f, g) << std::endl;
|
|
+------Creates a temporary object (rvalue)
rvalues无法绑定到非const引用,因此请改用const
引用
template <class T, int dim, bool isRowVec>
std::ostream& operator<<(std::ostream& os, const Vector<T, dim, isRowVec>& vec)
// ~~~~~
{
// ....
}
答案 1 :(得分:0)
在operator <<
中,您需要const & vec
而不是& vec
。
您无法将临时引用传递给非const引用,因此您无法通过crossProduct
调用的结果。