2

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.

7
  • @post that's gone: I dunno, it's just an exercise to get a feel for template metaprogramming. Let's say Concat, CharAt, ToString, and Length. Commented Oct 27, 2011 at 4:12
  • This code outputs "Hell" when I run it. It sounds like somebody's playing halloween pranks on you =) Commented Oct 27, 2011 at 4:14
  • can you use varadic templates? Commented Oct 27, 2011 at 4:14
  • Have you tried working with typedef String<'o', Null> myString; to start with and then work your way up the chain? Commented Oct 27, 2011 at 4:20
  • @Dani I was thinking about ways to use variadic templates for this one as well. It could reduce the nesting level perhaps. Commented Oct 27, 2011 at 4:21

1 Answer 1

3

"" + C + ToString<S>::str first performs pointer addition, and only later concatenation, to do string concatenation all the way do std::string("") + C + ToString<S>::str

Sign up to request clarification or add additional context in comments.

1 Comment

@R.MartinhoFernandes: he uses it as a static member.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.