错误:"at"没有依赖于模板参数的参数,因此at的声明必须可用

Ber*_*cia 6 c++ templates compiler-errors vector std

Noob在这里,

我正在尝试从Bjarne Stroustrup的'The C++ Programming Language'编译这段代码,但CodeBlocks一直在向我抛出这个错误.

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

这是代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

返回的错误是:

  • 'at'没有依赖于模板参数的参数,因此'at'的声明必须可用
  • 注意:(如果使用'-fpermissive',G ++将接受您的代码,但不允许使用未声明的名称
  • 在成员函数'const T&operator [](int i)const'中:
  • 'at'没有依赖于模板参数的参数,因此'at'的声明必须可用
  • 在此范围内未声明"进入"
  • 模板参数1无效
  • '('令牌)之前的声明中的无效类型

谁可以给我解释一下这个?

另外,如果我不使用'using namespace std;',我将如何实现呢?

Yak*_*ont 23

替换atvector<T>::atthis->at.

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

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

这有助于避免在实践中出现令人讨厌的意外,您认为方法调用变为全局调用,或者全局调用成为方法调用.它还允许更早地检查模板方法体.


nom*_*oma 5

除了Yakk的答案,另一种解决方案是添加

using vector<T>::at;

Vec基本上它加入的抬头功能列表.

通过这种方式,at()可以像往常一样使用前缀类型或者前缀this->.