【问题标题】:An issue with template method's instance and std::vector.begin() as argument模板方法的实例和 std::vector.begin() 作为参数的问题
【发布时间】: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 + nRandomAccessIterator 有这个要求,但InputIterator 没有)。 std::istream_iterator 是 InputIterator 的一个例子,它不是 RandomIterator。
  • 感谢您的评论!我发现的另一件事是模板方法必须在头文件中定义(在我的实际源代码中它是在 .cpp 中)。

标签: c++ templates vector iterator


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多