How to implement the Casts utility namespace

Let's say I am creating a namespace Casts

that will contain many drop 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 . 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 is, are there any other possible approaches to implement in an Casts

elegant, uniform and reliable way. The ideal way for me is to have an easy easy approach.

+3


source to share


1 answer


Yes, you can do what it boost::lexical_cast

does internally: use a stream. And you can combine your multiple functions into multiple 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 may need to specify specific overloads for the version wstring

(it will widen

), but that's about it.

+6


source







All Articles