Search code examples
c++variadic

Stroustrup 4th edition, page 82, variadic template example does not compile


The following is the gist of the code, which fails to compile on g++ 4.7.1

#include <iostream>
using namespace std;

template <typename T> void bottom(T x) {cout << x << " ";}

template <typename Head, typename Tail...> 
void recurse(Head h, Tail t) {bottom(h); recurse(t...)}

void recurse(){}

int main() { recurse(1,2.2); }

For reasons unknown, the "void recurse(){}" is not participating in the template recursion.

Looking for a clue.


Solution

  • There are a few syntactic problems with that code (I doubt that you copy-pasted as is from Bjarne's book), but after fixing them, it seems the main problem is that the overload of recurse() accepting no arguments appears only after the function template recurse().

    Moving it before it fixes the problem:

    #include <iostream>
    
    using namespace std;
    
    template <typename T>
    void bottom(T x) {cout << x << " ";}
    
    void recurse(){} // <== MOVE THIS BEFORE THE POINT WHERE IT IS CALLED
    
    template <typename Head, typename... Tail>
    void recurse(Head h, Tail... t)
    {
        bottom(h);
        recurse(t...);
    }
    
    int main() { recurse(1,2.2,4); }
    

    Here is a live example.