c++wrapperlexical-cast

lexical cast c++


how can we write a wrapper lexical cast function in order to implement lines like :

int value = lexical_cast<int> (string)

I am quite new to programming and was wondering how we can write the function. I don't know how to figure out a template. Also can we write a wrapper function for double too ? Like

double value = lexical_cast2<double> (string)

??


Solution

  • To have it as you stated in your example:

    #include <sstream>
    
    template <class Dest>
    class lexical_cast
    {
        Dest value;
    public:
        template <class Src>
        lexical_cast(const Src &src) {
            std::stringstream s;
            s << src;
            s >> value;
        }
    
        operator const Dest &() const {
            return value;
        }
    
        operator Dest &() {
            return value;
        }
    };
    

    Including error checking:

        template <class Src>
        lexical_cast(const Src &src) throw (const char*) {
            std::stringstream s;
            if (!(s << src) || !(s >> value) || s.rdbuf()->in_avail()) {
                throw "value error";
            }
        }