Boost logo

Boost Users :

Subject: [Boost-users] boost::lexical_cast: where to declare operator<<
From: Nagaev Boris (bnagaev_at_[hidden])
Date: 2011-09-07 05:03:29


Hello!

I'm implementing boost::lexical_cast for class A.
When operator<< is declared in the same namespace, as class A, it works:

* #include <boost/lexical_cast.hpp>
* #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_cast<std::string>(a);
* }

But if operator<< is declared in root namespace, it will not compile:

* #include <boost/lexical_cast.hpp>
* #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_cast<std::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<Target, Source,
Traits>::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<std::basic_string<char>, abc::A,
std::char_traits<char>
>*)this)->boost::detail::lexical_stream<std::basic_string<char>,
abc::A, std::char_traits<char> >::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.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net