模拟boost lexical_cast操作
Imitate boost lexical_cast operation
不幸的是,在我当前的项目中,我不能使用boost,所以我试图模仿boost::lexical_cast
的行为(减去boost所做的大部分错误检查)。我有以下功能,这些功能有效。
// Convert a string to a primitive, works
// (Shamelessly taken from another stack overflow post)
template <typename T>
T string_utility::lexical_cast(const string &in)
{
stringstream out(in);
T result;
if ((out >> result).fail() || !(out >> std::ws).eof())
{
throw std::bad_cast();
}
return result;
}
// Convert a primitive to a string
// Works, not quite the syntax I want
template <typename T>
string string_utility::lexical_cast(const T in)
{
stringstream out;
out << in;
string result;
if ((out >> result).fail())
{
throw std::bad_cast();
}
return result;
}
为了保持一致性,我希望能够对两者使用相同的语法,但我想不通。
将字符串转换为基元是可以的。
int i = lexical_cast<int>("123");
然而,另一种方式看起来是这样的:
string foo = lexical_cast(123);
// What I want
// string foo = lexical_cast<string>(123);
编辑:谢谢您我不得不切换模板参数,但以下内容正是我想要的。
template<typename Out, typename In> Out lexical_cast(In input)
{
stringstream ss;
ss << input;
Out r;
if ((ss >> r).fail() || !(ss >> std::ws).eof())
{
throw std::bad_cast();
}
return r;
}
lexical_cast
的基本模板代码是:
template<typename In, typename Out> Out lexical_cast(In in) {
stringstream ss;
ss << in;
if (ss.fail()) throw bad_cast();
ss >> out;
return out;
}
根据需要添加(In==string)等的错误检查和专业化。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何理解C++标准N3337中的expr.const.cast子句8
- 重载操作程序时出错>>用于类中的字符串 memebr
- C++Cast运算符过载
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- 此代码中的操作流程是什么?C/C++.
- 复制和交换习惯用法与移动操作之间的交互
- 像union_这样的 Boost.Geometry 操作如何处理浮点类型的基本不精确性?