C ++模板函数

时间:2016-01-14 20:28:29

标签: c++ overloading operator-keyword

此Vec模板支持多种功能,例如将矢量乘以标量并将矢量添加到另一个矢量。

令我困惑的是,为什么第二个operator*的重载超出了类模板? 在类中声明的operator*重载了vectorXscalar 在外面声明的那个支持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);

1 个答案:

答案 0 :(得分:0)

在模板类中声明的operator*同样可以在类外部写为

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

可以使用单个参数(表示rhs)在类中编写,因为隐含的*this参数用作运算符的lhs。

与类外定义的operator*的区别在于运算符的lhs是模板类型。这允许在使用运算符时提供参数。

您可以在具有任意lhs和rhs类型的类之外定义运算符,但在类中仅限于改变rhs。给定参数类型,编译器将选择任何定义的operator*的最佳匹配。