模拟boost lexical_cast操作

Imitate boost lexical_cast operation

本文关键字:cast 操作 lexical boost 模拟      更新时间:2023-10-16

不幸的是,在我当前的项目中,我不能使用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)等的错误检查和专业化。