c++c++11castinglexical-cast

How to implement Casts utility namespace


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.


Solution

  • 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.