Stroustrup第4版,第82页,可变模板示例无法编译

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

本文关键字:编译 4版 82页 Stroustrup      更新时间:2023-10-16

下面是代码的要点,在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); }

由于未知的原因,"void recurse(){}"没有参与模板递归。

寻找线索

这段代码有一些语法问题(我怀疑你复制粘贴了就像Bjarne的书中的一样),但在修复它们之后,似乎主要问题是recurse()不接受参数的过载只出现在函数模板recurse()之后。

在它解决问题之前移动它:

#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); }

下面是一个的实例

有很多错别字。

  1. 以下代码不正确

    template <typename Head, typename Tail...>
    

    应该是

    template <typename Head, typename... Tail>
    
  2. 参数包应扩展为...

    void recurse(Head h, Tail... t)
    
  3. 漏选;(...(再次)

    bottom(h); recurse(t...);
    
  4. void recurse() {}应该在模板函数之前声明,以允许不带参数地调用recurse

下面的代码可以工作:

#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);
}