Search code examples
c++operatorscomma-operator

C++ overide global operator comma gives error


the second function gives error C2803 http://msdn.microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx : 'operator ,' must have at least one formal parameter of class type. any clue?

template<class T,class A = std::allocator<T>> 
class Sequence : public std::vector<T,A> {
 public:
    Sequence<T,A>& operator,(const T& a) {
        this->push_back(a);
        return *this;
    }
    Sequence<T,A>& operator,(const Sequence<T,A>& a) {
        for(Sequence<T,A>::size_type i=0 ; i<a.size() ; i++) {
            this->push_back(a.at(i));
        }
        return *this;
    }
};

//this works!
template<typename T> 
Sequence<T> operator,(const T& a, const T&b) {
    Sequence<T> seq;
    seq.push_back(a);
    seq.push_back(b);
    return seq;
}

//this gives error C2803!
Sequence<double> operator,(const double& a, const double& b) {
    Sequence<double> seq;
    seq.push_back(a);
    seq.push_back(b);
    return seq;
}

Solution

  • Change that to:

    Sequence<double> operator,(const Sequence<double>& a, const double& b)
    {
        Sequence<double> seq(a);
        seq.push_back(b);
        return seq;
    }
    

    or (based on this article):

    Sequence<double> operator,(Sequence<double> seq, const double& b)
    {
        seq.push_back(b);
        return seq;
    }