C ++编译器如何处理模板 [英] C++ How do compilers handle templates

查看:53
本文介绍了C ++编译器如何处理模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可能从我最近的帖子中知道,我正在为参加C ++考试而学习,该课程的内容交付得很差.我基本上必须自学所有东西,所以请在这里忍受.

As some of you may know from my recent posts i am studying for a C++ exam which the content for the class was delivered very poorly. I am basically having to self teach everything myself so bear with me here.

这是一个考试问题:

(i)解释C ++语言中定义的模板的概念.确保区分程序员做什么和做什么编译器会这么做.

(i)Explain the concepts of templates as defined in the C++ language. Be sure to differentiate between what the programmer does and what the compiler does.

我当前的理由

(i)模板允许函数或类使用泛型进行操作.这样,程序员就可以一次有效地执行X程序功能,并且可以将其用于许多不同的数据类型,而不必多次重写应用程序或应用程序的一部分.

(i) A template allows a function or class to operate using generics. This allows the programmer to effective program X functionality once, and be able to use this functionality with many different data types without having to rewrite the application or parts of the application multiple times.

我的问题是我不知道编译器如何处理模板的使用.

My problem is i have no idea how the compiler handles the use of templates.

我不确定编译器在此阶段的工作,如果有人可以清除它会有所帮助.

I am unsure what the compiler does at this stage, if somebody could clear this up it would be helpful.

推荐答案

假设您使用模板编写函数:

let's say you write a function using templates:

template <typename T>
void function(T t){
 doSomething();
}

对于您调用此函数的每种数据类型,编译器只需用该数据类型替换"T",说"int",并为此生成代码,就像您已经用"int"而不是"T"编写了此函数从一开始.如果其他人同意,这可能是正确的(但不是完整的)答案.

for each data type you call this function, the compiler simply replaces the 'T' with that data type, say 'int' and generates code for that like you've written this function with 'int' instead of 'T' since the beginning. This is probably the right (but not the complete) answer if others agreed.

这篇关于C ++编译器如何处理模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆