C++ 中的模板是什么?
有人可以用简单的格式解释一下吗?
有模板函数和模板类。有什么优点和缺点?我听说模板的构建速度很慢,甚至在运行时也是如此?
真的?
谢谢
Can someone explain this in a simple format?
There are template functions and template classes. What are the advantages and disadvantages? I have heard that templates are slow to build and even at runtime?
True?
Thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C++ 中,您可以重载函数,例如:
模板允许您创建采用任意类型的“通用”函数或类。因此,您不必每次添加类型时都定义一个函数,而是可以定义一次,然后让编译器为您“编写”所有函数。
通过类,您可以根据类型差异创建变体。我能想到的最好的例子是 std::vector ..你可以将它视为容器/数组/任何东西。但是您需要预先定义类型(以便它知道每个元素有多大,如何复制每个元素等):
因为实际上发生的情况是编译器在编译时为您编写附加函数,因此不应该有任何运行时效果。不过,运行时可能会出现问题,因为您有太多的模板代码,这会导致代码膨胀,这可能会导致执行缓存未命中……但在当今的硬件上,这不应该是问题。
我看到的主要缺点是您通常必须将模板放在公开您的实现的头文件中。我还发现它们更难调试,因为它们会创建非常混乱的编译器错误消息。
In C++ you have the ability to overload functions eg:
Well, templates allow you to make "generic" functions or classes that take arbitrary types. So instead of defining a function each time you add a type, you can define it once, and let the compiler 'write' all the functions for you.
With classes you create variants based upon type differences. The best example I can think of is std::vector.. you can think of it as a container/array/whatever of anything. But you need to define the type upfront (so it knows how large each element is, how to copy each element, etc):
Because what is happening, in effect, is the compiler is writing the additional functions for you at compile time, there should not be any runtime effect. The issue at run time might arise though, where you have so much template code, which leads to bloat in the code, and this could lead to execution cache misses... but on today's hardware, that shouldn't be a problem.
The main disadvantage I see is that you have to put templates, generally, in the header file which exposes your implementation. I also find them harder to debug, because they can create quite messy compiler error messages.
总结一下:
如果您编写一个函数 add(int a, int b)?如果您的添加可以对所有数据类型执行此操作,不是很好吗?不只是 int 而不需要创建超过 1 个函数吗?这就是模板的用武之地。它们使您只需要一个函数即可封装多种类型。
这就是你如何创建这个函数:
To summarize it all up:
If your writing a function add(int a, int b)? Wouldn't it be nice if your add could do it for all datatypes? Not just int without the need to make more than 1 function? That's where templates come in. They make it so you only need one function to encapsulate many types.
This would be how you make the function: