I am new to template function and cannot figure this error. Hope you can help.
//utility.h
#ifndef UTILITY_H
#define UTILITY_H
# include <iostream> //for cout
# include <vector> //for vector
/*
* Print to the screen the content of a vector
* Define function template in the header
*/
template <typename T>
void print_vector(T& v)
{
for(typename std::vector<T>::const_iterator i = v.begin();
i != v.end(); ++i)
std::cout << *i << ' ';
}
#endif
//main.cpp
#include "utility.h"
int main(int argc, char * argv[])
{
std::vector<int> field;
field.resize(12, 1);
/*
for( std::vector<int>::const_iterator i = field.begin();
i != field.end(); ++i)
std::cout << *i << ' ';
*/
print_vector(field);
return 0;
}
The main.cpp failed to compile with a very long error message that I can't even insert here.
error: conversion from ‘std::vector::iterator {aka __gnu_cxx::__normal_iterator >}’ to non-scalar type ‘std::vector, std::allocator > >::const_iterator {aka __gnu_cxx::__normal_iterator*, std::vector, std::allocator > > >}’ requested utility.h:21:59: error: no match for ‘operator!=’ in ‘i != (& v)->std::vector<_Tp, _Alloc>::end >()’ utility.h:21:59: note: candidates are: In file included from /usr/include/x86_64-linux-gnu/c++/4.7/./bits/c++allocator.h:34:0, from /usr/include/c++/4.7/bits/allocator.h:48, from /usr/include/c++/4.7/string:43, from /usr/include/c++/4.7/bits/locale_classes.h:42, from /usr/include/c++/4.7/bits/ios_base.h:43, from /usr/include/c++/4.7/ios:43, from /usr/include/c++/4.7/istream:40, from /usr/include/c++/4.7/fstream:40, from utility.h:4: /usr/include/c++/4.7/ext/new_allocator.h:134:5: note: template bool __gnu_cxx::operator!=(const __gnu_cxx::new_allocator<_Tp>&, const __gnu_cxx::new_allocator<_Tp>&) /usr/include/c++/4.7/ext/new_allocator.h:134:5: note: template argument deduction/substitution failed: utility.h:21:59: note: ‘std::vector, std::allocator > >::const_iterator {aka __gnu_cxx::__normal_iterator*, std::vector, std::allocator > > >}’ is not derived from ‘const __gnu_cxx::new_allocator<_Tp>’
Aucun commentaire:
Enregistrer un commentaire