0
votes

getting this error:

C:\CodeBlocks\kool\praks3\vector.h|62|error: passing 'const Vector<2u>' as 'this' argument of 'std::string Vector::toString() [with short unsigned int n = 2u]' discards qualifiers|

with this code:

    #include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <sstream>

template <unsigned short n>
class Vector {
    public:
        std::vector<float> coords;

        Vector();
        Vector(std::vector<float> crds);


        float distanceFrom(Vector<n> v);

        std::string toString();

        template <unsigned short m>
        friend std::ostream& operator <<(std::ostream& out, const Vector<m>& v);
};



    template <unsigned short n>
std::string Vector<n>::toString() {
    std::ostringstream oss;

    oss << "(";
    for(int i = 0; i < n; i++) {
        oss << coords[i];
        if(i != n - 1) oss << ", ";
    }
    oss << ")";
    return oss.str();
}

template <unsigned short m>
std::ostream& operator<<(std::ostream& out, const Vector<m>& v) {
    out << v.toString(); // ERROR HEEEERE
    return out;
}
3
Congrats. So, what is your question? I don't see a single question mark in the above.AnT

3 Answers

4
votes

Make the toString method const:

std::string toString() const;

and

template <unsigned short n>
std::string Vector<n>::toString() const{...}

That's because you add the const qualifier to the Vector in the operator<<. You are only allowed to call const qualified methods on const qualified objects.

1
votes

This is because your vector is declared as const, while your toString operator is not a const method. Therefore, calling this method is forbidden with a const instant. If you do not edit the vector while converting it to string, you should declare it as a const method :

std::string toString() const;
0
votes

If you have a const Foo, you can only invoke const member functions on it. So declare it as std::string toString() const.