Search code examples
c++stringtemplatesmetaprogrammingc++11

C++ template string concatenation


I'm trying to define some variadic template like that:

typedef const char CCTYPE[];
template<CCTYPE X, CCTYPE... P> struct StringConcat { ... };

so that I could write sth like:

char foo[] = "foo"; char bar[] = "bar";
std::cout << StringConcat<foo, bar>;

and it printed foobar. How can I do this, if it's possible in C++0x?

my real interest is to solve FizzBuzz problem using c++ templates, I found a solution here to convert an int to char[] using templates.


Solution

  • #include <boost/mpl/string.hpp>
    #include <boost/mpl/insert_range.hpp>
    #include <boost/mpl/end.hpp>
    #include <iostream>
    
    using namespace boost;
    
    template < typename Str1, typename Str2 >
    struct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};
    
    int main()
    {
      typedef mpl::string<'hell', 'o'> str1;
      typedef mpl::string<' wor', 'ld!'> str2;
    
      typedef concat<str1,str2>::type str;
    
      std::cout << mpl::c_str<str>::value << std::endl;
    
      std::cin.get();
    }
    

    Using that construct you should be able to implement your FizzBuzz in pure metaprogramming. Nice exercise BTW.