Passing strings as a template parameter (small utility)

As you know, you can't pass a string as a template parameter. Nevertheless, I have found that I often need to do just that. This small utility allows you to pass a string as a parameter. I call it "static_string". This could possibly given to one of the google students as an easy project. Otherwise, here an example of what I do to solve this problem. typedef static_string<'H','E','L','P'> help_t; std::string help = help_t(); BOOST_CHECK(help == "help"); template <typename T> void foo() { std::string str = T(); BOOST_CHECK(str == "help"); } foo<help_t>(); template <char a=' ', char b=' ', char c=' ', char d=' ', char e=' ', char f=' ', char g=' ', char h=' '> char i=' '> char j=' '> char k=' '> char l=' '> struct static_string { operator std::string() { char ch[7]; sprintf(ch,"%c%c%c%c%c%c%c%c%c%c%c%c", a,b,c,d,e,f,g,h,i,h,k,l); std::string str = ch; boost::trim(str); return str; } };
participants (3)
-
Mathias Gaunard
-
Stefan Seefeld
-
Tom Brinkman