|
Boost : |
From: d.frey_at_[hidden]
Date: 2000-12-04 12:42:55
--- In boost_at_[hidden], "Peter Dimov" <pdimov_at_m...> wrote:
> Try this:
>
> template<std::size_t N> string lexical_cast_helper<string, char[N]>
> {
> static std::string call(char const * s)
> {
> return s;
> }
> };
Fantastic, thanks! I changed "string" to "class" in the first line and
it worked! Now, I think it's worth to resend the whole code. Kevlin,
you're reading this? I also added a specialization for T == S. Here it
is:
#include <iostream>
#include <string>
#include <strstream>
#include <typeinfo>
class bad_lexical_cast : public std::bad_cast
{
public:
virtual const char* what() const throw()
{
return "bad_lexical_cast";
}
};
template< typename T, typename S > class lexical_cast_helper
{
public:
static T call( const S& arg )
{
std::strstream interpreter;
T result;
if(!(interpreter << arg) ||
!(interpreter >> result) ||
!(interpreter >> std::ws).eof())
{
throw bad_lexical_cast();
}
return result;
}
};
template< typename T, typename S > T lexical_cast( const S& arg )
{
return lexical_cast_helper< T, S >::call( arg );
}
template< typename U > class lexical_cast_helper< U, U >
{
public:
static U call( const U& arg )
{
return arg;
}
};
template< typename T, size_t N > class lexical_cast_helper< T, char[N]
>
{
public:
static T call( const char* arg )
{
return lexical_cast< T >( std::string( arg ) );
}
};
int main()
{
try {
std::cout << lexical_cast< std::string >( std::string("Hello,
world!") ) << endl;
std::cout << lexical_cast< std::string >( "Hello, world!" ) <<
endl;
}
catch( std::exception& e ){
cerr << e.what();
}
return 0;
}
Regards, Daniel
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk