1

I'm trying to design a variadic template which takes a parameter pack (i.e, characters) and inserts these characters immediately into cout. I imagined that I can use a struct called for example PrintChars and do some sort of template recursion to reach every parameter in the parameter pack. I already succceeded to do this at runtime, but now I would like to do this at compile-time. I would like for example to have the following template call to print "foo" in the terminal.

cout << PrintChars<'f', 'o', 'o'>()

Do you have any ideas? Thanks.

jww
  • 97,681
  • 90
  • 411
  • 885
  • How do you plan to `cout` at compile time? – Chad Mar 01 '15 at 19:00
  • Oops, you are correct. I first need to store those characters at compile time in something like a struct and afterwards at run-time I need to write it to the output stream. Any ideas how to do this? – Daemonstool Mar 01 '15 at 19:09
  • To print some characters that are stored as a template parameter pack, you could store them in an array: `constexpr static char arr[] = {character_pack...};` or use one of the pack expansion tricks to call `cout << one_character` for each character: http://stackoverflow.com/a/28117353/ – dyp Mar 01 '15 at 20:07

1 Answers1

2

It's just a simple exercise in handling parameter packs. My PrintChars<...> doesn't really have any state, it just passes the parameter pack around.

http://ideone.com/39HcTG

#include <iostream>
using namespace std;

template<char... s>
struct PrintChars {};

std::ostream& operator<< (std::ostream& o, const PrintChars<>&)
{
    return o;
}

template<char head, char... tail>
std::ostream& operator<< (std::ostream& o, const PrintChars<head, tail...>& pc)
{
    o << head << PrintChars<tail...>();
    return o;
}

int main() {
    cout << PrintChars<'f', 'o', 'o'>();
    return 0;
}

The only 'metaprogramming' here is in creating the properly nested operator<< call.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458