简体   繁体   中英

An issue with template method's instance and std::vector.begin() as argument

I want to make an overloaded class operator() method that can take any kind of iterators (including pointers) as an arguments. I try to make this using templates:

class SimpleFunction
{
public:
    virtual double operator()(double x) = 0;
    template<class Iterator> void operator()(Iterator x, Iterator y, unsigned int n);
    void operator()(const vector<double> &x, const vector<double> &y);
};

template<class Iterator> void SimpleFunction::operator()(Iterator x, Iterator y, unsigned int n)
{
    while (x != x + n)
        *y++ = operator()(*x++);
}

void SimpleFunction::operator()(const vector<double> &x, const vector<double> &y)
{
    operator()(x.begin(), y.begin(), x.size());
}

But when i try to compile my code, i get an error:

D:\\MyFiles\\functions\\simple.cpp:9: error: C3892: 'y' : you cannot assign to a variable that is const

I cannot understand why i get this error, because std::vector must have begin() method, that returns non-const iterator. How can i avoid this error?

std::vector has const-overloaded begin and end member functions. Because of this, in the template call operator()(x.begin(), y.begin(), x.size()); , the Iterator is deduced to be vector<double>::const_iterator . If you mean to modify the passed-in vector y , don't have it be a const vector<double>& :

void SimpleFunction::operator()(const vector<double> &x, vector<double> &y)

Note that you will need to use two template type arguments instead of one, if you insist on x and y having different types:

template<class Iterator, class IteratorY> void SimpleFunction::operator()(IteratorX x, IteratorY y, unsigned int n)

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