关于模板函数实例化的编译时错误

时间:2011-10-01 09:11:38

标签: c++ templates iterator

我正在尝试用迭代器编写容器类。这是我的班级:

template <class T>
class C{
 private:
  T* v;
  int MAX_SIZE;
  int i;
 public:
  C (int size){
   MAX_SIZE = size;
   v = new T (MAX_SIZE);
   i = 0;
  }

 ~C(){ delete v; }

  class iterator{
   private:
    T* v;
   public:
    iterator(T* ip){ v = ip; }

    void operator++ (){ ++v; }
    void operator-- (){ --v; }
    T    operator*  () { return *v; }
    bool operator!= (const iterator & it) { return v != it.v; }
 };

 iterator begin(){ return iterator (v); }
 iterator end()  { return iterator (&v[MAX_SIZE]); }

 void push_back (T e){
   if (i == MAX_SIZE) throw MaxSizeReached();
   v[i] = e;  
   ++i;
 }

 class MaxSizeReached{};
};

template <class T>
void print(typename C<T>::iterator & start, typename C<T>::iterator & end){
 for (typename C<T>::iterator s (start), e (end); s != e; ++s){
   std::cout << *s << '\n';
 }
}

int main(){
 C<int> ic (3);
 C<float> fc (4);
 C<char> cc (3);

 ic.push_back (56);
 ic.push_back (76);
 ic.push_back (88);

 print<int>(ic.begin(), ic.end());

 return 0;
}

g ++ 4.5抛出此错误:

templatizedCustomIterator.c++: In function ‘int main()’:
templatizedCustomIterator.c++:71:35: error: no matching function for call to ‘print(C<int>::iterator, C<int>::iterator)

哪个不正确 - print()或电话的定义?

2 个答案:

答案 0 :(得分:3)

查看功能模板:

template<T>
void print(typename C<T>::iterator & start, typename C<T>::iterator & end);

你的用法:

 print(ic.begin(), ic.end());

所以问题是,T不能从函数参数中推断出来。标准称之为不可导入的上下文。在这里,我详细解释了类似的问题,请阅读:

现在问题是,你将如何实现功能模板?所以这是一个很好的解决方案:

template <class FwdIterator>
void print(FwdIterator start, FwdIterator end)
{
  for ( ;  start != end;  ++start)
  {
     std::cout << *start << '\n';
  }
}

如果您传递第三个参数:

template <class FwdIterator>
void print(FwdIterator start, FwdIterator end, std::ostream &out)
{
  for ( ;  start != end;  ++start)
  {
     out << *start << '\n';
  }
}

然后您也可以使用它来打印到文件:

 print(ic.begin(), ic.end(), std::cout); //print to console


 std::ofstream file("file.txt")
 print(ic.begin(), ic.end(), file); //print to file

答案 1 :(得分:0)

print函数必须将参数作为const引用,否则它不能与begin()end()返回的临时值一起使用:< / p>

template <class T>
void print(const typename C<T>::iterator & start, const typename C<T>::iterator & end){
   ...
}