模板中的方法:一个工作,一个不实例化

时间:2014-02-22 09:27:36

标签: c++ templates

 template <class T, int MAXSIZE>
 class svector {
 public:
     typedef T value_type;
     class iterator : public std::iterator<std::input_iterator_tag,T> {
     // ...
     };
 // ...
 svector::iterator insert( svector::iterator position, const T& val );
 void insert( svector::iterator position, size_t n, const T& val );
 svector::iterator erase( svector::iterator position );
 svector::iterator erase( svector::iterator first, svector::iterator last );
 // ...
 };

 template <class T, int MAXSIZE>
 class svector<T,MAXSIZE>::iterator svector<T,MAXSIZE>::insert (class svector<T,MAXSIZE>::iterator position, const T& val){
     insert( position, 1, val );
     return position;
 }

 template <class T, int MAXSIZE>
 void svector<T,MAXSIZE>::insert (class svector<T,MAXSIZE>::iterator position, size_t n, const T& val){
     // ...
 }

 template <class T, int MAXSIZE>
 class svector<T,MAXSIZE>::iterator ??????????????????????????????erase (class svector<T,MAXSIZE>::iterator position){
     return erase( position, position );  // (1)
 }

 template <class T, int MAXSIZE>
 class svector<T,MAXSIZE>::iterator ??????????????????????????????erase (class svector<T,MAXSIZE>::iterator first,
                                           class svector<T,MAXSIZE>::iterator last) {
     // ..
 }

insert方法已经过测试。但是非常相似的erase方法 不愿意,我不明白为什么。这是一个UT片段:

typedef class util::svector<int, 10> vecIntX;
vecIntX v1;
for( int e = 0; e < 10; e++ ) v1.push_back( e );
vecIntX::iterator it = v1.begin();
v1.erase( it );   // (2)

Eclipse在第(1)行抱怨:

"Invalid arguments, candidates are ? erase(?), ? erase(?,?)

第(2)行链接时出错:

undefined reference to 'util::svector<int, 10>::erase(util::svector<int, 10>::iterator)'

1 个答案:

答案 0 :(得分:1)

您需要在方法定义前加上类名:

template <class T, int MAXSIZE>
class svector { ... };

template <class T, int MAXSIZE>
class svector<T,MAXSIZE>::iterator svector<T,MAXSIZE>::erase(
    class svector<T,MAXSIZE>::iterator position){ ... }

当你在类之外内联方法时。