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

StackOverflow https://stackoverflow.com/questions/16750586

  •  30-05-2022
  •  | 
  •  

Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

There are a lot of typos.

  1. Following code is incorrect

    template <typename Head, typename Tail...>
    

    It should be

    template <typename Head, typename... Tail>
    
  2. Parameter pack should be expanded with ...

    void recurse(Head h, Tail... t)
    
  3. Missed ;, ( and ...(again)

    bottom(h); recurse(t...);
    
  4. void recurse() {} should be declared before template function to allow call recurse with no arguments.

The following code works:

#include <iostream>

using namespace std;

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

void recurse()
{

}

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

int main()
{
    recurse(1,2.2);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top