假设我生成了一个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
以优雅、统一和健壮的方式实现。对我来说,理想的方法是采用原生的轻量级方法。