jeudi 31 mars 2016

How to execute a function on first call in a recursive template function?

Question title says it all, so how do you execute a function on a first call in a recursive template function?


I thought of using default variables in the function signature, but there isn't a place where the variable doesn't interfere with the rest of the function signature. Here's what I mean:
template<typename T, typename... Ts>
void print(T first, Ts... params) { ... }

Note: I'm using a bool (b) to determine if the function wasn't called from itself.

  1. void print(bool b = true, T first, Ts... params);. Doesn't work if called with only 1 argument (i.e. print("hello");), because the compiler initializes b with "hello".
  2. void print(T first, bool b = true, Ts... params);. Doesn't work with multiple arguments (i.e. print("hello", "world", "again");), because the compiler initializes b with the second parameter in the parameter pack..
  3. void print(T first, Ts... params, bool = true);. Same as 2, except that b is initialized with the last parameter in the parameter pack.

What I would like is something like this (or something else involving template arguments if you want (or something completely different))

template<typename T, typename... Ts>
void print(T first, Ts... params)
{
    if (...) // Magic!
        foo();
    std::cout << first << '\n';

    print(params...);
}

Any ideas?

Aucun commentaire:

Enregistrer un commentaire