Interger -> String

Started by
15 comments, last by v0dKA 20 years ago
writing a lexical_class template isn''t hard. Check this out:

#include <string>#include <sstream>template<typename R, typename T> R lexical_cast(T const& val) { 	R ret; 	std::stringstream st; 	if(!(st<<val) || !(st>>ret)) {}// /* No bad_cast in stlport? */ throw std::bad_cast(); 	return ret; }
Advertisement
quote:Original post by Deyja
writing a lexical_class template isn''t hard. Check this out:
(snip)
There is one complication. What does this line do?
std::cout <<lexical_cast<std::string>("hi mom") << std::endl;
It prints the address of the string literal ''hi mom''. Duh.
It prints "hi". So I guess you lose.
Really? What compiler/stl implementation?

It printed a nice hex number for me. I suppose one of us has a non-standard overload for stringstream<<char*.
GCC 3.2 (and its supplied library implementation).

The issue which I meant to bring up was that it only reads the first token off, so casting to a string can lose information. Due to lack of compiler support for partial template specialisation, it can take a bit of trickery to get it working. The boost team can save you this trouble.
quote:Original post by Deyja
Really? What compiler/stl implementation?

It printed a nice hex number for me. I suppose one of us has a non-standard overload for stringstream<

You do. See 27.6.2.5.4 in the C++ standard.

This topic is closed to new replies.

Advertisement