C++ 模板只是伪装的宏吗?

2021-12-13 00:00:00 macros templates 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.

相关文章