0

This Vec template supports several functions such as multiplying a vector by scalar and adding vector to another vector.

The thing that is confusing me is that why the overloading of the second operator* is outside of the class template? The operator* which is declared in the class overloads vectorXscalar The one declared outside supports scalarXvector

template <class T>
class Vec {
public:
    typename list<T>::const_iterator begin() const {
        return vals_.begin();
    }
    typename list<T>::const_iterator end() const {
        return vals_.end();
    }
    Vec() {};

    Vec(const T& el);
    void push_back(T el);
    unsigned int size() const;
    Vec operator+(const Vec& rhs) const;
    Vec operator*(const T& rhs) const; //here
    T& operator[](unsigned int ind);
    const T& operator[](unsigned int ind) const;
    Vec operator,(const Vec& rhs) const;
    Vec operator[](const Vec<unsigned int>& ind) const;

    template <class Compare>
    void sort(Compare comp) {
        vals_.sort(comp);
    }

protected:
    list<T> vals_; 
};

template <class T>
Vec<T> operator*(const T& lhs, const Vec<T>& rhs); //and here!

template <class T>
ostream& operator<<(ostream& ro, const Vec<T>& v);
sijaan hallak
  • 47
  • 1
  • 8
  • Possible duplicate of [Function declaration inside or outside the class](http://stackoverflow.com/questions/9075931/function-declaration-inside-or-outside-the-class) – Cristina_eGold Jan 14 '16 at 22:21

1 Answers1

0

The operator* declared inside the template class could equally be written outside the class as

template <class T>
Vec<T> operator*(const Vec<T>& lhs, const T& rhs);

It can be written inside the class with a single argument (representing the rhs) because there is the implied *this argument used as the lhs of the operator.

The difference with the operator* defined outside the class is that the lhs of the operator is a template type. This allows the arguments to be supplied either way around when using the operator.

You are allowed to define the operator outside of a class with any arbitrary lhs and rhs types, but within the class are restricted to only varying the rhs. The compiler would select the best match of any defined operator* given the argument types.

pticawr
  • 551
  • 5
  • 8
  • Your first sentence with the code you provided made things that my Lecturer couldn't explain to me well! You sir know how to explain things dont you? Thanks!! :) – sijaan hallak Jan 14 '16 at 20:57