简体   繁体   中英

C++ “…does not name a type”

I've been trying to define a class method which uses a return type declared in the class namespace:

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 {
    //...
}

When I try to compile the code, I'm getting this error:

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

I Also tried to define the method like this:

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

And this:

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

Result:

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

What am I doing wrong?

The name iterator is scoped to your class and it is a dependent name. In order to use it you need to use the scope operator and the typename keyword

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

Live Example

As pointed out in the comment by MM you can also use the trailing return syntax as

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

Live Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM