【问题标题】:error: 'e' is not a class, namespace, or enumeration错误:“e”不是类、命名空间或枚举
【发布时间】:2016-10-04 07:47:05
【问题描述】:

我正在尝试重载运算符

error: 'e' is not a class, namespace, or enumeration

这是我的代码:

#include <iostream>
#include <vector>

template<typename T>
std::ostream& operator<<(std::ostream &out, T const &e){
    for(e::iterator it = e.begin(); it != e.end(); it = it + 2){
        out << *it << " ";
    }
    return out;
} 

int main(){
    std::vector<int> v;
    for(int i= 0; i < 10; i++){
        v.push_back(i);
    }

    std::cout << v;
    return 0;
}

【问题讨论】:

  • T::iterator替换e::iterator
  • 使用auto &amp;&amp;it

标签: c++ templates stl iterator


【解决方案1】:

这里有两个问题。

一个是e::iterator。您不能通过对象访问成员类型,您需要使用该类型。相反,您应该只使用auto it = e.begin()。如果你不能使用 C++11,那么你需要使用

typename T::const_iterator it = e.begin()

需要typename,因为名称依赖于模板参数,需要const_iterator 而不仅仅是iterator,因为参数标记为const

但是,您更严重的错误在于首先使此重载。

template<typename T>
std::ostream& operator<<(std::ostream &out, T const &e){

这声明了 任何类型std::ostream 输出的重载。这肯定会让你头疼,而且,果然,如果你修复了第一个错误,你会在尝试输出" "时得到一个模棱两可的函数调用错误:

main.cpp:7:20: error: use of overloaded operator '<<' is ambiguous (with operand types '__ostream_type' (aka 'basic_ostream<char, std::char_traits<char> >') and 'const char [2]')
        out << *it << " ";
        ~~~~~~~~~~ ^  ~~~

如果您真的想在每个标准库容器中使用此功能,我想您检查是否存在类似 T::iterator 的内容,并且只有在存在时才启用您的重载。像这样的:

template<typename T, typename = typename T::iterator>
std::ostream& operator<<(std::ostream &out, T const &e){
    for(auto it = e.begin(); it != e.end(); it = it + 2){
        out << *it << " ";
    }
    return out;
} 

Live demo

【讨论】:

    猜你喜欢
    • 2016-03-27
    • 2014-07-24
    • 2011-07-08
    • 1970-01-01
    • 2016-04-20
    • 2014-04-09
    • 2016-06-22
    • 1970-01-01
    相关资源
    最近更新 更多