C++ "...does not name a type"

标签 c++ templates gcc using

我一直在尝试定义一个使用类命名空间中声明的返回类型的类方法:

template<class T, int SIZE>
class SomeList{

public:

    class SomeListIterator{
        //...
    };

    using iterator = SomeListIterator;

    iterator begin() const;

};

template<class T, int SIZE>
iterator SomeList<T,SIZE>::begin() const {
    //...
}

当我尝试编译代码时,出现此错误:

Building file: ../SomeList.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"SomeList.d" -MT"SomeList.d" -o "SomeList.o" "../SomeList.cpp"
../SomeList.cpp:17:1: error: ‘iterator’ does not name a type
 iterator SomeList<T,SIZE>::begin() const {
 ^
make: *** [SomeList.o] Error 1

我也试过这样定义方法:

template<class T, int SIZE>
SomeList::iterator SomeList<T,SIZE>::begin() const {
    //...
}

还有这个:

template<class T, int SIZE>
SomeList<T,SIZE>::iterator SomeList<T,SIZE>::begin() const {
    //...
}

结果:

Building file: ../SomeList.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"SomeList.d" -MT"SomeList.d" -o "SomeList.o" "../SomeList.cpp"
../SomeList.cpp:17:1: error: invalid use of template-name ‘SomeList’ without an argument list
 SomeList::iterator SomeList<T,SIZE>::begin() const {
 ^
make: *** [SomeList.o] Error 1

我做错了什么?

最佳答案

名称 iterator 的范围仅限于您的类,并且它是一个从属名称。为了使用它,您需要使用范围运算符和 typename 关键字

typename SomeList<T,SIZE>::iterator SomeList<T,SIZE>::begin() const

Live Example

正如 M.M 的评论中指出的那样您还可以使用尾随返回语法作为

auto SomeList<T,SIZE>::begin() const -> iterator {

Live Example

关于C++ "...does not name a type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553393/

相关文章:

c++ - 调试读/写字符串到二进制文件

c++ - static 在这里的目的是什么?

c - 如何在 Ubuntu 上解决错误消息 "gcc‬: command not found"(仅带参数)

c++ - c_include_path 与 ld_library_path

c++ - 是否有 QFileinfo::Owner() 的 Windows 等价物?

c++ - (Qt C++)运行一个大循环后报错(愿意付费)

c++ - C++模板泛型(模板参数列表)

c++ - 模板的类型转换

c++ - 如何从模板结构创建二维数组

c++ - 为什么 const 左值引用可以引用可变右值引用?