Monday, October 11, 2010

Easy generic toString() function in C++

In c++ you can make a simple toString() template function that converts primitives to a string.


#include <iostream>
using namespace std;

template<typename T>
string toString(T t) {
stringstream s;
s << t;
return s.str();
}


This will work for any type that defines the << operator for use with streams.

So with this simple one function we have an "int to string" function, a "float to string" function, a "double to string" function, etc...

Using it is of course simple:

int main() {
string s0 = toString(100);
string s1 = toString(100.1f);
string s2 = toString(100.12);
cout << s0 << " " << s1 << " " << s2 << endl;
return 0; // Prints out "100 100.1 100.12"
}

3 comments:

  1. Interesting use. I only heard of template functions but I never actually understood the use. It's pretty clear now.

    ReplyDelete
  2. Hi man!
    I'm ElectroFuzz from The Game Programming Wiki.
    You commented my post there and made me curious so i came here....

    Well, I liked your blog and I decided to start making my own eum, or, why not optimize yours...
    I'm speaking seriously.

    ReplyDelete
  3. Hi ElectroFuzz, I'm glad you were inspired by my blog.
    Currently my emu isn't open source yet, as i described in the last comment on this blog post:
    http://cottonvibes.blogspot.com/2010/09/nes-emu-progress.html#comments

    I want to have my emulator in a good state before it goes open source, since i want to do as much as possible on my own.

    I do encourage you to make your own emu as its a great learning experience and a fun project to work on.
    Best of luck!

    ReplyDelete