[C++-sig] vector<> to string
François Duranleau
duranlef at iro.umontreal.ca
Sat May 6 19:43:10 CEST 2006
On Fri, 5 May 2006, Andreas Beyer wrote:
> // convert vector into python-style string
> std::ostream& operator<<(std::ostream& os, const std::vector<VALUE_T>& v) {
[...]
> }
The problem is here. boost::lexical_cast relies on ADL to find the
appropriate operator<<. However, in the case for int, it cannot find it
because the operator is declared outside of the namespace std (that is,
this operator is not in the list of "friends" to std::vector<int>; and it
seems that base types have to associated namespaces). However, in the case
of MyInt, it is declared in the global namespace, thus allowing ADL to
look in the global namespace as well for the operator.
The simple solution is to declare the operator<< in namespace std.
Actually, it is usually better, I think, to declare operators in the same
namespace as the manipulated types.
P.S.: In the definition of your operator, you use:
operator<<(os, lexical_cast<std::string>(*it));
Why bother with the lexical_cast here? Why not simply write:
os << *it;
? It would also be more efficient.
--
François Duranleau
LIGUM, Université de Montréal
"Nothing will ever be attempted, if all possible objections must be first
overcome."
- Samuel Johnson, 1759.
More information about the Cplusplus-sig
mailing list