Stroustrup第4版,第82页,可变模板示例无法编译
Stroustrup 4th edition, page 82, variadic template example does not compile
下面是代码的要点,在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); }
下面是一个的实例
有很多错别字。
-
以下代码不正确
template <typename Head, typename Tail...>
应该是
template <typename Head, typename... Tail>
-
参数包应扩展为
...
void recurse(Head h, Tail... t)
-
漏选
;
、(
和...
(再次)bottom(h); recurse(t...);
-
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);
}
相关文章:
- 如何在Visual studio 2017社区版中编译字节币源代码
- 无法在安卓版 QT 上编译
- 如何编译适用于较旧 Linux 发行版的二进制文件
- 使用MinGW gcc/g++(nuwen发行版)编译的程序出现运行时错误
- C++:ifstream getline 问题交叉编译到 OpenWRT 发行版中
- 是否对在另一个Linux发行版中使用G 编译的可执行文件有限制
- 旧版 MFC 代码 (2005) 无法在 VC 2010 上编译
- GNU GCC:尝试编译发行版时对"WinMain@16"的未定义引用(代码::Blocks)
- 在编译 Android 版 OpenCV Core 模块时,包含 Eclipse 中未解析的指令引用
- 当我为调试Lua编译程序时,运行得很好,但为什么我要为发布版编译它,我得到了一个c0000005错误
- Microsoft Visual C++2010学习版-编译错误
- 发布编译旧版0.9.0 c++客户端
- Stroustrup第4版,第82页,可变模板示例无法编译
- 编译c++与boost所有linux发行版
- Cocos 编译 -p 安卓在 3.7 版上不起作用
- 无法使用Microsoft visual studio c++ 2008 express版编译c代码
- 编译一个在所有Linux发行版中执行而不重新编译的C/ c++源代码是否可能?
- 编译 Android 版 Qt:"mingw32-make"不被识别为内部或外部命令
- 在Linux上编译一个共享库以针对所有发行版
- 编译iOS版OpenCV失败-Cmake失败