如何实现Casts实用程序命名空间
How to implement Casts utility namespace
假设我生成了一个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
),但仅此而已
相关文章:
- C++实用程序::转换在静态链接库中不起作用
- 通过实用程序 fn 将捕获的 lambda 传递给 C 样式回调 - 错误
- 当我尝试进行TPC-E测试时,实用程序抱怨"undefined reference"
- 在没有格式说明符的情况下在c++中使用类似printf的实用程序
- C++实用程序,用于将长开关语句转换为封装开关案例阶梯的简洁函数调用
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- C :实用程序名称空间中的正态分布
- 实用程序函数不会在 .h 文件中初始化并在 main 中定义.cpp
- 用于创建integral_constants的 aribtrary 元组的通用实用程序
- Qt 创建器中的实用程序::转换::to_string_t中的链接错误
- 硬币或CBC求解器性能:命令行实用程序与编译的C 程序
- 位置实用程序例程与使用类型相同的命名空间
- 对于C++ Vector3 实用程序类实现,数组是否比结构和类快?
- 如何设计一个配置实用程序来静态和动态链接工作
- OS X"堆"命令行实用程序如何收集其信息?
- readelf 实用程序用于 Visual Studio C++ ABI 和 VS 编译的对象
- 卡在C++编写我的差异实用程序
- (GSTREAMER)如何使Taglib和Core Audio实用程序类一起工作
- 在 C++ 中创建通用实用程序类
- 如何实现Casts实用程序命名空间