【问题标题】:Error in template function with iterators [duplicate]带有迭代器的模板函数出错[重复]
【发布时间】:2016-09-01 13:50:24
【问题描述】:

我想确定向量中的元素是否是其邻居之间的平均值,所以我编写了这个程序

#include <iostream>
#include <vector>
using namespace std;

template <typename T>
bool is_avg(vector<T>::iterator x) {         <-- error line
    T l = *(x - 1), m = *x, r = *(x + 1);
    return x * 2 == l + r;
}

int main() {
    vector<int> v;
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    cout << (is_avg(v.begin() + 1) ? "Yes" : "No");
    return 0;
}

但它不起作用

main.cpp|6|error: template declaration of 'bool is_avg'

怎么了?

【问题讨论】:

    标签: c++ templates stl


    【解决方案1】:

    两件事:第一,你应该使用m * 2而不是x * 2,并且你不能从vector&lt;T&gt;::iterator推导出T。相反,使用It 作为模板参数:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    template <typename It>
    bool is_avg(It x) {        // <-- error line
        auto const& l = *(x - 1), m = *x, r = *(x + 1);
        return m * 2 == l + r;
    }
    
    int main() {
        vector<int> v;
        v.push_back(2);
        v.push_back(3);
        v.push_back(4);
        cout << (is_avg(v.begin() + 1) ? "Yes" : "No");
    }
    

    Live Example

    【讨论】:

    • 谢谢。 (x * 2 是一个意外错误)。你能解释一下为什么不能从vector&lt;T&gt;::iterator 推断出T 吗?我可以在不使用auto 的情况下创建T 类型的变量吗(例如在C++98 中)?
    • @Pavel 本质上(详见重复问答),编译器必须将模式vector&lt;T&gt;::iterator 与传递的参数进行匹配,但这样做时,它只能查看一般形式模式,而不是“在它里面”。人们使用的另一个短语是编译器无法看到 :: 之外的内容,这就是 iterator 不匹配的原因。
    猜你喜欢
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 2018-07-20
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多