Specifying template parameters

I want to write my own vector class and function that calculates the cross product.

My class vector has

template<class T, int dim, bool isRowVector>

      

T is the record type, dim size and isRowVector determines whether the vector is a row or a column vector.

I have overloaded some Vector operators, in particular <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;
}

      

Now the crossProduct function should only be applied to vectors with dim = 3. So I set a function like this:

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;
}

      

excluding the dim parameter in the function template, as it doesn't need to be guessed or specified.

This does not seem to be a problem since

Vector<float,3,true> a = crossProduct(f,g);

      

does not generate a compilation error where f and g are both

Vector<float,3,true>

      

But when I try to call

std::cout << crossProduct(f, g) << std::endl;

      

I get

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;
            ^

      

Any ideas?

+3


source to share


2 answers


std::cout << crossProduct(f, g) << std::endl;
             |
             |
             +------Creates a temporary object (rvalue)

      

rvalues ​​cannot bind to non-const references, so use reference const

instead



template <class T, int dim, bool isRowVec>
std::ostream& operator<<(std::ostream& os, const Vector<T, dim, isRowVec>& vec) 
//                                         ~~~~~
{
   // ....
}

      

+2


source


In yours operator <<

you need const & vec

, not & vec

.



You cannot pass a temporary reference to a non-const reference, so you cannot pass the result of the call crossProduct

.

0


source







All Articles