错误:'at' 没有依赖于模板参数的参数,因此必须提供 at 声明

2021-12-31 00:00:00 compiler-errors templates vector c++ std

这里的菜鸟

我正在尝试从 Bjarne Stroustrup 的C++ 编程语言"中编译这段代码,但 CodeBlocks 一直向我抛出这个错误.

I'm trying to compile this segment of code from Bjarne Stroustrup's 'The C++ Programming Language' but CodeBlocks keeps throwing me this error.

该代码是关于检查向量函数中保存的数组的范围.

The code is about range checking an array held in a vector function.

代码如下:

#include <iostream>
#include <vector>
#include <array>

using namespace std;

int i = 1000;

template<class T> class Vec : public vector<T>
{
public:
    Vec() : vector<T>() { }

    T& operator[] (int i) {return at(i); }
    const T& operator[] (int i) const {return at(i); }
    //The at() operation is a vector subscript operation 
    //that throws an exception of type out_of_range
    //if its argument is out of the vector's range.
};

Vec<Entry> phone_book(1000);

int main()
{

    return 0;
}

返回的错误是:

  • 'at' 没有依赖于模板参数的参数,因此必须有一个 'at' 声明
  • 注意:(如果您使用-fpermissive",G++ 将接受您的代码,但不推荐使用未声明的名称
  • 在成员函数 'const T& 中运算符 [] (int i) const':
  • 'at' 没有依赖于模板参数的参数,因此必须有一个 'at' 声明
  • 未在此范围内声明条目"
  • 模板参数 1 无效
  • '(' 标记前的声明类型无效

有人可以向我解释一下吗?

Can someone explain this to me?

另外,如果我不使用using namespace std;",我将如何实现这一点

Also, how would I implement this if I were to not use 'using namespace std;'

推荐答案

vector::atthis->at 替换 at.

与最初设计 C++ 时相比,现在关于如何在模板中查找函数的规则更加严格.

Rules for how functions are looked up in templates are tighter now than when C++ was being originally designed.

现在,只有当您this-> 时,才会查找依赖基类中的方法,否则假定它是全局函数(或非依赖基类/本地类/等).

Now, methods in dependent bases are only looked up if you this->, otherwise it is assumed to be a global function (or a non-dependent base/class local/etc).

这有助于在实践中避免令人讨厌的意外,在这种情况下,您认为的方法调用变成了全局调用,或者全局调用变成了方法调用.它还允许提前检查模板方法主体.

This can help avoid nasty surprises in practice, where what you thought was a method call becomes a global one, or a global call becomes a method call. It also allows earlier checking of template method bodies.

相关文章