I'm just starting out with template metaprogramming so I'm just trying to make some basic things to begin with. I got Size and Lookup "methods" working for a BST, so I decided to try making a String class. I have this code in a cpp file:
#include <iostream>
#include <string>
using namespace std;
struct Null;
// String
template <char C, typename S>
struct String {
static const char chr = C;
typedef S tail;
};
// ToString
template <typename S>
struct ToString;
template <char C, typename S>
struct ToString<String<C, S> > {
static const string str;
};
template <char C, typename S>
const string ToString<String<C, S> >::str = C + ToString<S>::str; // (*)
template <char C>
struct ToString<String<C, Null> > {
static const string str;
};
template <char C>
const string ToString<String<C, Null> >::str = C + ""; // to make it a string
int main() {
typedef String<'H', String<'e', String<'l', String<'l',
String<'o', Null> > > > > myString;
cout << ToString<myString>::str << endl;
return 0;
}
This code outputs "Hell" when I run it. What am I doing wrong in the base case? It seems to have something to do with the "", because I used to have C + ToString<S>::str as "" + C + ToString<S>::str on line (*) and the output then was random junk.
typedef String<'o', Null> myString;to start with and then work your way up the chain?