c++ - Overloading of << operator using iterator as a parameter -
i`d print enum values text , use overloading. suppose have following code:
#include <iostream> #include <map> #include <string> #include <vector> #include <unordered_set> enum enm{ one, 2 }; class complex{ public: friend std::ostream& operator<<(std::ostream& out, std::unordered_multiset<int>::const_iterator i){ switch (*i){ case one:{ return out<<"one"; } case two:{ return out << "two"; } } } void func(std::unordered_multiset<int> _v); }; void complex:: func(std::unordered_multiset<int> _v){ _v.insert(one); _v.insert(two); (std::unordered_multiset<int>::const_iterator i(_v.begin()), end(_v.end()); != end; ++i){ std::cout <<"num: " << *i <<std::endl; //need here "one", "two" instead of 0, 1 } } int main(){ complex c; std::unordered_multiset<int> ms; c.func(ms); return 0; }
the problem variant doesn`t work. so, 0, 1 instead of one, two. have no ideas how properly. thank help!
i'm assuming changed i
*i
in order program compile. in order print iterator must i
, fails compiler error.
the problem insertion operator defined friend within class on first declaration, lookup find operator can depend on namespaces , classes associated argument types, lookup referred adl or koenig lookup.
since std::ostream
, unordered_multiset::const_iterator
not asscoiated complex
(see adl#details
), lookup fails find insertion operator.
the solution declare function outside of class normal unqualified lookup operator takes place:
std::ostream& operator<<(std::ostream&, std::unordered_multiset<int>::const_iterator); class complex { .. };
i recommend define operator outside of class, doesn't seem need access private/protected members of complex
(part of purpose of befriending entities).
Comments
Post a Comment