Hello!
I'm implementing boost::lexical_cast for class A.
When operator<< is declared in the same namespace, as class A, it works:
* #include
* #include <string>
*
* namespace abc {
*
* struct A {
* int a;
* };
*
* std::ostream& operator<<(std::ostream& o, const A& a) {
* return o << a.a;
* }
*
* }
*
* int main() {
* abc::A a;
* std::string a_str = boost::lexical_caststd::string(a);
* }
But if operator<< is declared in root namespace, it will not compile:
* #include
* #include <string>
*
* namespace abc {
*
* struct A {
* int a;
* };
*
* }
*
* std::ostream& operator<<(std::ostream& o, const abc::A& a) {
* return o << a.a;
* }
*
* int main() {
* abc::A a;
* std::string a_str = boost::lexical_caststd::string(a);
* }
Part of error message:
In file included from error.cpp:2:0:
/usr/include/boost/lexical_cast.hpp: In member function ‘bool
boost::detail::lexical_stream::operator<<(const Source&) [with Target =
std::basic_string<char>, Source = abc::A, Traits =
std::char_traits<char>]’:
/usr/include/boost/lexical_cast.hpp:1151:13: instantiated from
‘Target boost::detail::lexical_cast(typename
boost::call_traits<Source>::param_type, CharT*, size_t) [with Target =
std::basic_string<char>, Source = abc::A, bool Unlimited = true, CharT
= char, typename boost::call_traits<Source>::param_type = const
abc::A&, size_t = long unsigned int]’
/usr/include/boost/lexical_cast.hpp:1174:77: instantiated from
‘Target boost::lexical_cast(const Source&) [with Target =
std::basic_string<char>, Source = abc::A]’
error.cpp:19:59: instantiated from here
/usr/include/boost/lexical_cast.hpp:595:48: error: no match for
‘operator<<’ in
‘((boost::detail::lexical_stream
*)this)->boost::detail::lexical_stream::stream << input’
/usr/include/c++/4.5/ostream:108:7: note: candidates are:
So, it does not see my declaration.
However,
<code>std::cout << a << std::endl;</code>
works in both cases.
What is the reason of this error?
Why operator<< can not be declared in root namespace?
Sorry for my question. Maybe, it is connected less to boost than to c++.
Regards.