c++ - Iterator and templates -
i try manipulate iterators.
template <typename mytype> class myclass { public: myclass ( const mytype & myarg) { this->data=myarg; } ~myclass ( void ){} set<int> test ( const mytype & myarg ) const { set<int> result; typename mytype::iterator it=myarg.begin(); return result; } private: // mutable mytype data; }; this code compiling.but when want use it, no longer compiling: here example:
int main() { myclass <string> t0 ( "caacaa" ); set<int> r=t0.test("a"); return 0; } i error:
test.cpp: in member function ‘std::set<int> myclass<mytype>::test(const mytype&) const [with mytype = std::basic_string<char>]’: test.cpp:38:26: instantiated here test.cpp:25:48: error: conversion ‘std::basic_string<char>::const_iterator {aka __gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >}’ non-scalar type ‘std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ requested i tried figure out wrong don't understand error.
in const member function, member data const too. need use const_iterator:
typename mytype::const_iterator = myarg.begin(); because myarg.begin() returns const iterator, because myarg const, because member function const.
even better use auto:
auto = myarg.begin(); but still need know it const — auto helps avoid typing long name, not knowing fact it const.
Comments
Post a Comment