LeviX
LeviX

Reputation: 3167

Imitate boost lexical_cast operation

Unfortunately, in my current project I can't use boost, so I am trying to imitate the behavior of boost::lexical_cast (minus most of the error checking boost does). I have the following functions, which work.

// 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;
}

I was hoping to be able to use the same syntax for both for consistency, but I can't figure it out.

Converting a string to a primitive is fine.

int i = lexical_cast<int>("123");

The otherway, however, looks like this:

string foo = lexical_cast(123);

// What I want
// string foo = lexical_cast<string>(123);

Edit: Thanks ecatmur I had to switch the template parameters around, but the following does exactly what I want.

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;
}

Upvotes: 1

Views: 206

Answers (1)

ecatmur
ecatmur

Reputation: 157534

The basic template code for lexical_cast is:

template<typename In, typename Out> Out lexical_cast(In in) {
    stringstream ss;
    ss << in;
    if (ss.fail()) throw bad_cast();
    ss >> out;
    return out;
}

Add error checking and specialisations for (In == string), etc. as desired.

Upvotes: 4

Related Questions