2

I've got templated code that uses lexical_cast.

Now I want to remove all the lexical_cast calls (because it doesn't work well with /clr).

I need to cast object between std::string and their value.

So, the first direction is easy (T _from, std::string _to) :

std::ostringstream os;
os << _from;
_to =  os.str();

But I can't think of a way to do it generically from a string to any type (I need something generic that will work with templates, can't just use specializations for each type and use functions like atoi)

Edit:

Of course I've tried using the ostringstream in the opposite direction. I get this error:

error C2784: 'std::basic_istream<_Elem,_Traits> &std::operator >>(std::basic_istream<_Elem,_Traits> &&,_Elem *)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &&' from 'std::ostringstream'

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185

1 Answers1

3

lexical_cast uses streaming in both directions, << and >>. You could do the same:

std::stringstream sstr;
sstr << _from;
sstr >> _to;

Be sure to include sanity checks though.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Tried that of course... I get this error: error C2784: 'std::basic_istream<_Elem,_Traits> &std::operator >>(std::basic_istream<_Elem,_Traits> &&,_Elem *)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &&' from 'std::ostringstream' – Yochai Timmer Jul 31 '11 at 11:06
  • 1
    @Yochai You are trying to use an `ostringstream`! Of course, that only allows output streaming, not input streaming. Use a `stringstream` instead. – Konrad Rudolph Jul 31 '11 at 11:11
  • Lol, didn't event notice the o there... been looking at the code for too long. Thanks – Yochai Timmer Jul 31 '11 at 11:14