1

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) 

??

4 Answers 4

6

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"; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

I much prefer this version!
1

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

6 Comments

I think you mean double value = FromString<double>(myString);
@Markus Schumann - so what's template , i am sorry , i still haven't looked into it. I started programming few months back. I have a class called Rectangle .
@stardust_ Code has changed since I made that comment.
@novice7 Templates are how you solve this problem. You had better start reading up on a very big topic.
Even after your edit you have it wrong. You should have just accepted the one line change i proposed =). Template function must still be called with type specified, unless you wrap it inside a class... FromString<double>(value,myString);
|
1

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() ); 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.