3

Say I generate a Casts namespace which will hold numerous casts functions:

namespace Casts
{
    // To string
    bool Cast(bool bValue,                 string& res);
    bool Cast(int intValue,                string& res);
    bool Cast(float floatValue,            string& res);
    bool Cast(const wstring& str,          string& res);

    // From string
    bool Cast(const string& strVal, bool& res);
    bool Cast(const string& strVal, int& res);
    bool Cast(const string& strVal, long& res);
    bool Cast(const string& strVal, float& res);

    // And lots of other casting functions of different types 
}

I really like boost:lexical_cast approach. For example:

bool Cast(int intValue, string& res)
{
    bool bRes = true;
    try { res = lexical_cast<string>(intValue); }
    catch(bad_lexical_cast &) { bRes = false; }
    return bRes;
}

My question, are there any other possible approaches to implement Casts in an elegant, uniform and robust manner. The ideal way for me is to have a native lightweight approach.

idanshmu
  • 5,061
  • 6
  • 46
  • 92
  • 3
    For C++11, also take a look at [`std::to_string`](http://en.cppreference.com/w/cpp/string/basic_string/to_string) for conversion of numerical types to strings. – ComicSansMS Sep 18 '14 at 09:32

1 Answers1

6

Yes, you can basically do what boost::lexical_cast does internally: use a stream. And you can merge your many functions into a few function templates:

namespace Casts
{

template <class From>
bool Cast(From val, string &res)
{
  std::ostringstream s;
  if (s << val) {
    res = s.str();
    return true;
  } else {
    return false;
  }
}

template <class To>
bool Cast(const string &val, To &res)
{
  std::istringstream s(val);
  return (s >> res);
}

}

You might need to provide specific overloads for the wstring version (playing around with widen in them), but that's about it.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455