$include_dir="/home/hyper-archives/boost/include"; include("$include_dir/msg-header.inc") ?>
From: d.frey_at_[hidden]
Date: 2000-12-01 07:57:00
Hi,
I think I found out why the old version used 'S arg' instead of 'const
S& arg'. I tried to specialize lexical_cast. I failed to specialize
for T == S, I managed to specialize lexical_cast< string, string > and
I managed to specialize lexical_cast< string, const char* > but I had
to replace 'const S& arg' by 'S arg' to make the last one work. Here's
some code:
#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 > T lexical_cast( S arg )
{
   cout << "1.";
 
   std::strstream interpreter;
   T result;
   if(!(interpreter << arg) ||
      !(interpreter >> result) ||
      !(interpreter >> std::ws).eof())
   {
      throw bad_lexical_cast();
   }
   return result;
}   
/* How to specialize for T == S ???
   
template< typename U > template<> U lexical_cast< U, U >( U arg )
{
   cout << "X.";
      
   return arg;
}
*/
// Only neccessary if the above isn't possible:
template<> string lexical_cast< string, string >( string arg )
{
   cout << "2.";
      
   return arg;
}
// This only work for lexical_cast's argument being declared as 'S
arg' and not 'const S& arg'
template<> string lexical_cast< string, const char* >( const char* arg
)
{
   cout << "3.";
      
   return 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