samedi 23 septembre 2017

variadic template recursion with sizeof..., but compile error: no matching function

I write a variadic template to print all the arguments with recursion:

#include <iostream>
using std::ostream; using std::istream;
using std::cin; using std::cout; using std::endl;

template <typename T, typename... Args>
ostream &myprint(ostream &os, const T &t, const Args&... rest) {
    if (sizeof...(rest)) {
        os << t << ", ";
        return myprint(os, rest...);
    }
    else
        return os << t;
}

int main(int argc, char *argv[]) {
    myprint(cout, "hello");
    return 0;
}

But when I compiles it with g++ -std=c++1y, it complains:

error: no matching function for call to ‘myprint(std::ostream&)’
     return myprint(os, rest...);

In the function myprint, I have checked the value of sizeof...(rest). And when it is 0, it will not call myprint(os, rest...). So I don't know why it will call myprint(std::ostream&).

And I have also searched for the related question, I have found that it need a base case. But why do I need a base case, and can't sizeof... work in a variadic template?

Aucun commentaire:

Enregistrer un commentaire