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

Are C++ Templates just Macros in disguise?(C++ 模板只是伪装的宏吗?)
本文介绍了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++ 模板只是伪装的宏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)