Quote:Original post by leiavoia
That would work, but i would like to not introduce more libs or dependencies than i have to. Those make it harder to finally install on someone else's machine as i've learned.
*cough* ParaGUI *cough* :-)
So far, i'm only using SDL and OpenGL. I'm using TinyXML also, but that doesn't count as a lib since it compiles directly into your project.
Haha, yes, indeed. ParaGUI...
Well, I guess you could roll your own quick little version of the caster. It's really easy to do actually. I just made one copy that seems to work just fine. The caster itself is here:
// File: cast.h#include <sstream>namespace cast { // Just a little exception to throw in case something goes wrong. // Note here, that you may want to derive from std::bad_cast or // something, just to make sense out of this class. class BadCast {}; //Local static stream to use when casting. static std::stringstream stream; // This is where the magic happens. You can cast anything into // anything else, elthough of course casting say float to double // would be silly using this. template< typename Target, typename Source > Target lexical_cast(Source arg) { //Create a placeholder for the result, of the type according to the template. Target result; //Clear stream, so if there's old junk in there, it goes away. stream.clear(); //Stringinize the argument, and check that everything went along fine. stream << arg; if (stream.fail()) { throw BadCast(); } //Convert the string to whatever it is we want here: stream >> result; if (stream.fail()) { throw BadCast(); } //Return the result: return result; }}
And so then you can use this as follows:
#include <iostream>#include "cast.h"int main() { std::string intStr = "123"; std::string floatStr = "3.1415926"; int num = cast::lexical_cast<int>(intStr); float fPi = cast::lexical_cast<float>(floatStr); double dPi = cast::lexical_cast<double>(floatStr); std::cout << "Converted " << intStr << " to (int)" << num << std::endl; std::cout << "Converted " << floatStr << " to (float)" << fPi << std::endl; std::cout << "Converted " << floatStr << " to (double)" << dPi << std::endl; return 0;}
The output of the above then is:
Converted 123 to (int)123Converted 3.1415926 to (float)3.14159Converted 3.1415926 to (double)3.14159Press any key to continue
Of course, the fact that the pi has too few digits up there is only due to the way I printed the float and the double. If you look through the debugger at the real values, no precision was lost in the cast.
Vovan