【发布时间】:2015-11-17 12:12:50
【问题描述】:
我想创建一个重载类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:\MyFiles\functions\simple.cpp:9: error: C3892: 'y' : you cannot assign to a variable that is const
我不明白为什么会出现这个错误,因为std::vector 必须有begin() 方法,它返回非常量迭代器。
我怎样才能避免这个错误?
【问题讨论】:
-
你的两个容器都是常量。这意味着 begin() 和 end() 返回 const_interator
-
[OT]:请注意,所有迭代器都没有定义
x + n(RandomAccessIterator 有这个要求,但InputIterator 没有)。 std::istream_iterator 是 InputIterator 的一个例子,它不是 RandomIterator。 -
感谢您的评论!我发现的另一件事是模板方法必须在头文件中定义(在我的实际源代码中它是在 .cpp 中)。
标签: c++ templates vector iterator