Domanda

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)

??

È stato utile?

Soluzione

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

Altri suggerimenti

you could try something like this:

#include <sstream>
#include <iostream>

template <class T>
void FromString ( T & t, const std::string &s )
{
    std::stringstream str;
    str << s;
    str >> t;
}

int main()
{
   std::string myString("42.0");

   double value = 0.0;

   FromString(value,myString);

   std::cout << "The answer to all questions: " << value;

   return 0;
}

If this is not an excersice and if your goal is just to convert string to other types:

If you are using C++11, there are new conversion functions.

so you can do something like

std::stoi -> int
std::stol -> long int
std::stoul -> unsigned int
std::stoll -> long long
std::stoull -> unsigned long long
std::stof -> float
std::stod -> double
std::stold -> long double 

http://www.cplusplus.com/reference/string/

If not C++11 you can use

int i = atoi( my_string.c_str() )
double l = atof( my_string.c_str() );

You could simple use this header. And write stuff liketo<std::string>(someInt) or to<unsigned byte>(1024). The second part will throw and tell you that you're doing bad stuff.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top