C++ 模板只是变相的宏吗? [英] Are C++ Templates just Macros in disguise?

查看:21
本文介绍了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++ 模板只是变相的宏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆