模板方法的实例和 std::vector.begin() 作为参数的问题

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

本文关键字:参数 问题 vector 实例 std 模板方法 begin      更新时间:2023-10-16

我想创建一个重载类operator()方法,它可以接受任何类型的迭代器(包括指针)作为参数。我尝试使用模板:

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

但是当我试图编译我的代码时,我得到一个错误:

D:MyFilesfunctionssimple.cpp:9: error: C3892: 'y' : you cannot assign to a variable that is const

我不明白为什么我得到这个错误,因为std::vector必须有begin()方法,返回非常量迭代器。我怎样才能避免这个错误?

std::vector具有const重载的beginend成员函数。因此,在调用operator()(x.begin(), y.begin(), x.size());的模板中,Iterator被推导为vector<double>::const_iterator。如果你想修改传入的矢量y,不要让它是const vector<double>&:

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

请注意,如果您坚持要求xy具有不同的类型,则需要使用两个模板类型参数,而不是一个:

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