C ++模板是伪装的宏吗? [英] Are C++ Templates just Macros in disguise?

查看:164
本文介绍了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设计中,一个ging叨的想法不断回到我:他们只是一个宏,真的...你可以实现(而不是UGLY)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



  • 中的Inscrutable编译器错误, t期望他们?

  • 代码膨胀?

  • 难以跟踪代码?

  • 设置调试器断点?

  • Inscrutable compiler errors in places where you don't expect them?
  • Code bloat?
  • Difficulty in tracing code?
  • Setting Debugger Breakpoints?

推荐答案

宏是一种文本替换机制。

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天全站免登陆