如何实现Casts实用程序命名空间

ida*_*hmu 3 c++ casting lexical-cast c++11

假设我生成一个Casts名称空间,它将包含许多强制转换函数:

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 
}
Run Code Online (Sandbox Code Playgroud)

我真的很喜欢boost:lexical_cast方法.例如:

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

我的问题是,是否有任何其他可能的方法以Casts优雅,统一和稳健的方式实施.对我来说,理想的方法是采用原生轻量级方法.

Rei*_*ica 6

是的,你基本上可以做boost::lexical_cast内部的事情:使用流.您可以将许多功能合并到一些功能模板中:

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);
}

}
Run Code Online (Sandbox Code Playgroud)

您可能需要为该wstring版本提供特定的重载(widen在其中使用),但这就是它.