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
As pointed out in the comment by M.M you can also use the trailing return syntax as
auto SomeList<T,SIZE>::begin() const -> iterator {