C++ 模板的优点和缺点是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/622659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:20:20  来源:igfitidea点击:

What are the good and bad points of C++ templates?

c++templates

提问by fmsf

I've been talking with friends and some completely agree that templates in C++ should be used, others disagree entirely.

我一直在与朋友交谈,有些人完全同意应该使用 C++ 中的模板,其他人则完全不同意。

Some of the good things are:

一些好处是:

  • They are more safe to use (type safety).
  • They are a good way of doing generalizations for APIs.
  • 它们使用起来更安全(类型安全)。
  • 它们是对 API 进行泛化的好方法。

What other good things can you tell me about C++ templates?

你能告诉我关于 C++ 模板的其他好处吗?

What bad things can you tell me about C++ templates?

你能告诉我关于 C++ 模板的哪些坏事?

Edit: One of the reasons I'm asking this is that I am studying for an exam and at the moment I am covering the topic of C++ templates. So I am trying to understand a bit more on them.

编辑:我问这个的原因之一是我正在为考试而学习,目前我正在讨论 C++ 模板的主题。所以我试图更多地了解它们。

回答by Anonymous

Templates are a very powerful mechanism which can simplify many things. However to use them properly requires much time and experience - in order to decide when their usage is appropriate.

模板是一种非常强大的机制,可以简化很多事情。然而,正确使用它们需要大量的时间和经验——以便决定何时使用它们是合适的。

For me the most important advantages are:

对我来说,最重要的优势是:

  • reducing the repetition of code (generic containers, algorithms)
  • reducing the repetition of code advanced (MPL and Fusion)
  • static polymorphism (=performance) and other compile time calculations
  • policy based design (flexibility, reusability, easier changes, etc)
  • increasing safety at no cost (i.e. dimension analysis via Boost Units, static assertions, concept checks)
  • functional programming (Phoenix), lazy evaluation, expression templates (we can create Domain-specific embedded languages in C++, we have great Proto library, we have Blitz++)
  • other less spectacular tools and tricks used in everyday life:
    • STL and the algorithms (what's the difference between forand for_each)
    • bind, lambda (or Phoenix) ( write clearer code, simplify things)
    • Boost Function (makes writing callbacks easier)
    • tuples (how to genericly hash a tuple? Use Fusion for example...)
    • TBB (parallel_forand other STL like algorithms and containers)
  • Can you imagine C++ without templates? Yes I can, in the early times you couldn't use them because of compiler limitations.
  • Would you write in C++ without templates? No, as I would lose many of the advantages mentioned above.
  • 减少代码重复(通用容器、算法)
  • 减少代码的重复高级(MPL 和 Fusion)
  • 静态多态性(=性能)和其他编译时计算
  • 基于策略的设计(灵活性、可重用性、更容易的更改等)
  • 免费提高安全性(即通过 Boost Units 进行维度分析、静态断言、概念检查)
  • 函数式编程(Phoenix)、惰性求值、表达式模板(我们可以用 C++ 创建领域特定的嵌入式语言,我们有很棒的 Proto 库,我们有 Blitz++)
  • 日常生活中使用的其他不太引人注目的工具和技巧:
    • STL 和算法(for和之间有什么区别for_each
    • 绑定,lambda(或 Phoenix)(编写更清晰的代码,简化事情)
    • Boost 函数(使编写回调更容易)
    • 元组(如何对元组进行一般散列?例如使用 Fusion...)
    • TBB(parallel_for以及其他类似 STL 的算法和容器)
  • 你能想象没有模板的 C++ 吗?是的,我可以,在早期,由于编译器限制,您无法使用它们。
  • 你会在没有模板的情况下用 C++ 编写吗?不,因为我会失去上面提到的许多优点。

Downsides:

缺点:

  • Compilation time (for example throw in Sprit, Phoenix, MPL and some Fusion and you can go for a coffee)
  • People who canuse and understand templates are not that common (and these people are useful)
  • People who think that they canuse and understand templates are quite common (and these people are dangerous, as they can make a hell out of your code. However most of them after some education/mentoring will join the group mentioned in the previous point)
  • template exportsupport (lack of)
  • error messages could be less cryptic (after some learning you can find what you need, but still...)
  • 编译时间(例如加入 Sprit、Phoenix、MPL 和一些 Fusion,你可以去喝杯咖啡)
  • 人们谁可以使用和理解模板并不常见(和这些人都是有用的)
  • 人们谁认为他们可以使用和理解模板是很常见(和这些人都是危险的,因为它们可以使地狱出你的代码,但是他们最一番教育后/指导将加入前一个点中提到的组)
  • 模板export支持(缺乏)
  • 错误消息可能不那么神秘(经过一些学习,你可以找到你需要的东西,但仍然......)

I highly recommend the following books:

我强烈推荐以下书籍:

回答by Colin

On the positive side, C++ templates:

从积极的方面来说,C++ 模板:

  • Allow for generalization of type

  • Decrease the amount of redundant code you need to type

  • Help to build type-safe code

  • Are evaluated at compile-time

  • Can increase performance (as an alternative to polymorphism)

  • Help to build very powerful libraries

  • 允许类型泛化

  • 减少需要输入的冗余代码量

  • 帮助构建类型安全的代码

  • 在编译时评估

  • 可以提高性能(作为多态的替代方案)

  • 帮助构建非常强大的库

On the negative side:

在消极方面:

  • Can get complicated quickly if one isn't careful

  • Most compilers give cryptic error messages

  • It can be difficult to use/debug highly templated code

  • Have at least one syntactic quirk ( the >> operator can interfere with templates)

  • Help make C++ very difficult to parse

  • 如果一个人不小心,很快就会变得复杂

  • 大多数编译器给出神秘的错误信息

  • 使用/调试高度模板化的代码可能很困难

  • 至少有一个语法怪癖(>> 运算符会干扰模板)

  • 帮助使 C++ 很难解析

All in all, careful consideration should be used as to when to use templates.

总而言之,应该仔细考虑何时使用模板。

回答by Ofek Shilon

My 2care rather negative.

我的 2c是相当负面的。

C++ types were never designed to perform compile time calculations. The notion of using types to achieve computational goals is very clearly a hack – and moreover, one that was never sought but rather stumbled upon

C++ 类型从未设计为执行编译时计算。使用类型来实现计算目标的概念很明显是一种黑客行为——而且,一种从未被人寻求过,而是偶然发现的

..

..

The reward for using MP in your code is the moment of satisfaction of having solved a hard riddle. You did stuff in 100 lines that would have otherwise taken 200. You grinded your way through incomprehensible error messages to get to a point where if youneeded to extend the code to a new case, you would know the exact 3-line template function to overload. Your maintainers, of course, would have to invest infinitely more to achieve the same.

在你的代码中使用 MP 的奖励是解决一个难题的满足感。您用 100 行代码完成了原本需要 200 行代码的工作。您通过难以理解的错误消息苦苦挣扎,最终达到了这样的程度,如果需要将代码扩展到新案例,您将知道确切的 3 行模板函数超载。当然,您的维护者必须投入无限多的资金才能实现相同的目标。

回答by Ofek Shilon

Good points: powerful; allows you to:

优点:强大;允许您:

  • prescribe compile-time attributes and computation
  • describe generic algorithms and datastructures
  • do many other things that would otherwise be repetitive, boring, and mistake-prone
  • does them in-language, without macros (which can be far more hazardous and obscure!)
  • 规定编译时属性和计算
  • 描述通用算法和数据结构
  • 做许多其他的事情,否则会重复、无聊且容易出错
  • 它们是用语言编写的,没有宏(这可能更加危险和晦涩!)

Bad points: powerful; allows you to:

缺点:强大;允许您:

  • provoke compile-time errors that are verbose, misleading, and obscure (though not as obscure and misleading as macros...)
  • create obscure and hazardous misdesigns (though not as readily as macros...)
  • cause code bloat if you're not careful (just like macros!)
  • 引发冗长、误导和晦涩的编译时错误(尽管不像宏那样晦涩难懂……)
  • 创建模糊和危险的错误设计(虽然不像宏那么容易......)
  • 如果您不小心会导致代码膨胀(就像宏一样!)

Templates vastly increase the viable design space, which is not necessarily a bad thing, but it does make them that much harder to use well. Template code needs maintainters who understand not just the language features, but the design consequences of the language features; practically speaking, this means many developer groups avoid all but the simplest and most institutionalized applications of C++ templates.

模板极大地增加了可行的设计空间,这不一定是一件坏事,但它确实使它们更难很好地使用。模板代码需要的维护者不仅要了解语言特性,还要了解语言特性的设计结果;实际上,这意味着许多开发人员团体都避免使用 C++ 模板的最简单和最制度化的应用程序。

In general, templates make the language much more complicated (and difficult to implement correctly!). Templates were not intentionally designed to be Turing-complete, but they are anyway -- thus, even though they can do just about anything, using them may turn out to be more trouble than it's worth.

通常,模板使语言变得更加复杂(并且难以正确实现!)。模板并不是有意设计为图灵完备的,但无论如何它们都是 - 因此,即使它们几乎可以做任何事情,但使用它们可能会带来更多的麻烦而不是它的价值。

回答by Dan Olson

Templates should be used sparingly.

应谨慎使用模板。

"Awful to debug" and "hard to read" aren't great arguments against good template uses with good abstractions.

“糟糕的调试”和“难以阅读”并不是反对使用良好抽象的良好模板的有力论据。

Better negative arguments would go towards the fact that the STL has a lot of "gotchas", and using templates for purposes the STL already covers is reinventing the wheel. Templates also increase link time, which can be a concern for some projects, and have a lot of idiosyncrasies in their syntax that can be arcane to people.

更好的否定论据会指向 STL 有很多“陷阱”的事实,并且将模板用于 STL 已经涵盖的目的是在重新发明轮子。模板还会增加链接时间,这对某些项目来说可能是一个问题,并且在其语法中有很多对人们来说可能很神秘的特性。

But the positives with generic code reuse, type traits, reflection, smart pointers, and even metaprograms often outweigh the negatives. The thing you have to be sure of is that templates are always used carefullyand sparingly. They're not the best solution in every case, and often not even the second or third best solution.

但是,通用代码重用、类型特征、反射、智能指针甚至元程序的积极作用往往超过消极作用。你必须要确定的事情是,模板总是用认真谨慎。在每种情况下,它们都不是最佳解决方案,通常甚至不是第二或第三个最佳解决方案。

You need people with enough experience writing them that they can avoid all the pitfalls and have a good radar for when the templates will complicate things more than helping.

你需要有足够经验的人来编写它们,他们可以避免所有的陷阱,并且对模板何时会使事情变得复杂而不是帮助有一个很好的了解。

回答by j_random_hacker

One of the disadvantages I haven't seen mentioned yet is the subtle semantic differences between regular classes and instantiations of class templates. I can think of:

我还没有看到提到的缺点之一是常规类和类模板的实例化之间的细微语义差异。我能想到:

  1. typedefed typenames in ancestor types aren't inherited by template classes.
  2. The need to sprinkle typenameand templatekeywords in appropriate places.
  3. Member function templates cannot be virtual.
  1. typedef祖先类型中的 ed 类型名不会被模板类继承。
  2. 需要在适当的地方洒typenametemplate关键字。
  3. 成员函数模板不能是virtual.

These things can usually be overcome, but they're a pain.

这些事情通常可以克服,但它们很痛苦。

回答by Alexis Pautrot

Some people hate templates (I do) because:

有些人讨厌模板(我讨厌),因为:

  • On maintainability pov, the wrong use of templates can have a negative effect ten times stronger than the initial advantage of time they were supposed to bring.
  • On optimization pov, compiler optimizations they allow are nothing compared to an optimal algorithm and the use of multi threading.
  • On compiling time pov, wrong use of templates can a very negative effect on parsing, compilation and linking phases, when poorly written templated declaration brings tons of useless parasite declarations in each compilation units (here is how 200 lines of code can produce an .obj of 1Mb).
  • 在可维护性观点上,模板的错误使用所产生的负面影响可能比它们应该带来的最初时间优势强十倍。
  • 在优化 pov 中,与最佳算法和多线程的使用相比,它们允许的编译器优化微不足道。
  • 在编译时间 pov,模板的错误使用会对解析、编译和链接阶段产生非常负面的影响,当编写不当的模板化声明会在每个编译单元中带来大量无用的寄生声明(这里是 200 行代码如何生成 .obj 1Mb)。

To me templates are like a chainsaw with an integrated flame thrower that can also launch grenades. One time in my life I may have a specific need of that. But most of the time, I'm using a regular hammer and a simple saw to build things and I'm doing a pretty good job that way.

对我来说,模板就像一个带有集成火焰喷射器的链锯,它也可以发射手榴弹。在我生命中的某个时候,我可能有特定的需求。但大多数时候,我使用普通的锤子和简单的锯子来建造东西,我用这种方式做得很好。

回答by Alexis Pautrot

I don't see how they are hard to read. What is unreadable about

我看不出它们有多难读。什么是不可读的

vector <string> names;

for example? What would you replace it with?

例如?你会用什么来代替它?

回答by Vinay

Advantage: Generic Datatypes can be created.

优点:可以创建通用数据类型。

Disadvantage: Code Bloating

缺点:代码膨胀

回答by lsalamon

Reusable code is made with template. Its application is in accordance with the profile of each.

可重用的代码是用模板制作的。它的应用是根据每个的配置文件。