简体   繁体   中英

C++ template functions

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM