問(wèn)題描述
我已經(jīng)用 C++ 編程幾年了,我已經(jīng)使用了很多 STL 并且創(chuàng)建了幾次我自己的模板類來(lái)看看它是如何完成的.
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.
現(xiàn)在我正在嘗試將模板更深入地集成到我的 OO 設(shè)計(jì)中,一個(gè)煩人的想法不斷回到我的腦海中:它們只是一個(gè)宏,真的......你可以使用 #defines 實(shí)現(xiàn)(相當(dāng)丑陋)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.
這種對(duì)模板的思考方式幫助我理解我的代碼實(shí)際上是如何工作的,但我覺(jué)得我一定是在某種程度上忽略了這一點(diǎn).宏是邪惡的化身,但模板元編程"風(fēng)靡一時(shí).
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.
那么,真正的區(qū)別是什么?以及模板如何避免#define 導(dǎo)致的危險(xiǎn),例如
So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like
- 難以理解的編譯器錯(cuò)誤您不希望它們出現(xiàn)的地方?
- 代碼膨脹?
- 難以跟蹤代碼?
- 設(shè)置調(diào)試器斷點(diǎn)?
推薦答案
宏是一種文本替換機(jī)制.
Macros are a text substitution mechanism.
模板是一種功能圖靈完備的語(yǔ)言,在編譯時(shí)執(zhí)行并集成到 C++ 類型系統(tǒng)中.您可以將它們視為語(yǔ)言的插件機(jī)制.
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.
這篇關(guān)于C++ 模板只是偽裝的宏嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!