[英]compile time error regarding template function instantiation
I am trying to write a container class with iterator. 我试图用迭代器编写一个容器类。 This is my class: 这是我的课:
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 throws this error: 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)
Which is incorrect - definition of print() or the call? 哪个不正确-print()或调用的定义?
Have a look the function template: 看一下功能模板:
template<T>
void print(typename C<T>::iterator & start, typename C<T>::iterator & end);
And your usage: 和您的用法:
print(ic.begin(), ic.end());
So the problem is, T
cannot be deduced from the function argument. 所以问题是,不能从函数参数推导出T
The Standard calls it non-deducible context . 该标准称其为不可推论的上下文 。 Here I've explained similar question in detail, read this: 在这里,我已经详细解释了类似的问题,请阅读以下内容:
Now the question is, how would you implement the function template? 现在的问题是,您将如何实现功能模板? So here is one good solution: 因此,这是一个很好的解决方案:
template <class FwdIterator>
void print(FwdIterator start, FwdIterator end)
{
for ( ; start != end; ++start)
{
std::cout << *start << '\n';
}
}
If you pass a third argument as: 如果您将第三个参数传递为:
template <class FwdIterator>
void print(FwdIterator start, FwdIterator end, std::ostream &out)
{
for ( ; start != end; ++start)
{
out << *start << '\n';
}
}
then you can use this to print to file as well: 那么您也可以使用它来打印到文件:
print(ic.begin(), ic.end(), std::cout); //print to console
std::ofstream file("file.txt")
print(ic.begin(), ic.end(), file); //print to file
The print
function has to take the parameters as const
references, else it can't be used with temporary values like those returned by begin()
and end()
: print
函数必须将参数作为const
引用,否则不能与begin()
和end()
返回的那些临时值一起使用:
template <class T>
void print(const typename C<T>::iterator & start, const typename C<T>::iterator & end){
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.