【问题标题】:error: there are no arguments to 'at' that depend on a template parameter, so a declaration of at must be available错误:'at' 没有依赖于模板参数的参数,因此 at 的声明必须可用
【发布时间】:2015-06-06 02:13:09
【问题描述】:

这里是菜鸟,

我正在尝试从 Bjarne Stroustrup 的“C++ 编程语言”编译这段代码,但 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;
}

返回的错误是:

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

谁能给我解释一下?

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

【问题讨论】:

  • 从 stl 容器继承时,您应该知道它们没有虚拟析构函数。当您的子类获取应该在其析构函数中释放的资源时,这可能会导致问题。
  • 最后一个问题很简单:要么在每个来自namespace std 的名字前面写上std::,例如到处写std::vector,或者写一次using std::vector(而不是namespace,只列出你使用的所有个人名字)
  • 这个错误的 MSVC++ 版本是“函数声明必须可用,因为没有任何参数依赖于模板参数”

标签: c++ templates vector compiler-errors std


【解决方案1】:

将at 替换为vector&lt;T&gt;::at 或this-&gt;at。

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

现在,仅当您 this-&gt; 时才会查​​找依赖基中的方法,否则假定它是全局函数(或非依赖基/类本地/等)。

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

【讨论】:

    【解决方案2】:

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

    using vector&lt;T&gt;::at;

    到Vec 基本上将其添加到查找函数列表中。

    这样,at() 可以照常使用,无需在其前面加上基类类型或this-&gt;。

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 2012-04-14
      • 2017-03-07
      • 1970-01-01
      • 2019-03-16
      • 2023-01-24
      • 2011-11-02
      • 2014-06-07
      • 1970-01-01
      相关资源
      最近更新 更多