Are C++ Templates just Macros in disguise?(C++ 模板只是伪装的宏吗?)
问题描述
我已经用 C++ 编程几年了,我已经使用了很多 STL 并且创建了几次我自己的模板类来看看它是如何完成的.
I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.
现在我正在尝试将模板更深入地集成到我的 OO 设计中,一个烦人的想法不断回到我的脑海中:它们只是一个宏,真的......你可以使用 #defines 实现(相当丑陋)auto_ptrs,如果你真的想要.
Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.
这种对模板的思考方式帮助我理解我的代码实际上是如何工作的,但我觉得我一定是在某种程度上忽略了这一点.宏是邪恶的化身,但模板元编程"风靡一时.
This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.
那么,真正的区别是什么?以及模板如何避免#define 导致的危险,例如
So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like
- 难以理解的编译器错误您不希望它们出现的地方?
- 代码膨胀?
- 难以跟踪代码?
- 设置调试器断点?
推荐答案
宏是一种文本替换机制.
Macros are a text substitution mechanism.
模板是一种功能图灵完备的语言,在编译时执行并集成到 C++ 类型系统中.您可以将它们视为语言的插件机制.
Templates are a functional turing-complete language that is executed at compile time and is integrated into the C++ type system. You can think of them as a plugin mechanism for the language.
这篇关于C++ 模板只是伪装的宏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 模板只是伪装的宏吗?


基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16