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

How to implement Casts utility namespace

本文关键字:Casts 实用程序 命名空间 实现 何实现      更新时间:2023-10-16

假设我生成了一个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 
}

我真的很喜欢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;
}

我的问题是,有没有其他可能的方法来以优雅、统一和健壮的方式实现Casts。对我来说,最理想的方法是使用原生的轻量级方法。

是的,您基本上可以做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);
}
}

您可能需要为wstring版本提供特定的重载(在其中使用widen),但仅此而已