Rob*_*inW 1 c++ gcc templates 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 {
//...
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译代码时,我收到此错误:
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
Run Code Online (Sandbox Code Playgroud)
我也尝试定义这样的方法:
template<class T, int SIZE>
SomeList::iterator SomeList<T,SIZE>::begin() const {
//...
}
Run Code Online (Sandbox Code Playgroud)
还有这个:
template<class T, int SIZE>
SomeList<T,SIZE>::iterator SomeList<T,SIZE>::begin() const {
//...
}
Run Code Online (Sandbox Code Playgroud)
结果:
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
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
该名称iterator的范围是您的类,它是一个从属名称.要使用它,您需要使用范围运算符和typename关键字
typename SomeList<T,SIZE>::iterator SomeList<T,SIZE>::begin() const
Run Code Online (Sandbox Code Playgroud)
正如MM的评论中所指出的,你也可以使用尾随返回语法
auto SomeList<T,SIZE>::begin() const -> iterator {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2147 次 |
| 最近记录: |