【问题标题】:Stroustrup 4th edition, page 82, variadic template example does not compile [closed]Stroustrup 第 4 版,第 82 页,可变参数模板示例无法编译 [关闭]
【发布时间】:2013-05-25 14:38:42
【问题描述】:

以下是代码的要点,在 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(){}”没有参与模板递归。

寻找线索。

【问题讨论】:

    标签: c++ variadic


    【解决方案1】:

    该代码存在一些语法问题(我怀疑您是否按原样复制粘贴了 Bjarne 书中的 ),但在修复它们之后,主要问题似乎是 @ 的重载987654322@ 不接受参数仅出现在函数模板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); }
    

    这是live example

    【讨论】:

    • 啊,谢谢。在第 4 版第 82 页中,它实际上出现在之后。抱歉打错了,目前在虚拟和主机之间进行剪切和粘贴。
    • @phunctor:如果它出现在它之后,那确实是一个错误。很高兴它有帮助:)
    • 向 Stroustrup 报告了错误,回复是“谢谢”
    • @phunctor:干得好,也许他没有太多时间;)
    【解决方案2】:

    有很多错别字。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多