简体   繁体   English

我应该何时使用模板以及何时重载函数?

[英]When should I use templates and when overloaded functions?

I am confused.我很困惑。 I never seem to decide what to use, a template or an overloaded function.我似乎从未决定使用什么,模板或重载的 function。 Overloads need more coding.重载需要更多的编码。 So in what cases is it preferred to use templates and in what overloaded functions?那么在什么情况下更倾向于使用模板以及在哪些重载函数中呢?

For example, i recently had to take this decision while making a small GBA game.例如,我最近在制作一个小型 GBA 游戏时不得不做出这个决定。 There were two types u16 and int and i decided to use overloaded functions.有两种类型u16int ,我决定使用重载函数。

inline void Point::Move(int x, int y) {_ix += x; _iy += y; }
inline void Point::Move(u16 x, u16 y) {_ix += (int) x; _iy += (int) y; }

should I have used a template instead?我应该改用模板吗? And in what cases should I use an overloaded function?在什么情况下我应该使用过载的 function?

Basic Rule should be:基本规则应该是:

Use Templates when you want to perform same functionality/Operations on different data types .当您想对不同的数据类型执行相同的功能/操作时,请使用模板

Use overloaded functions when you want to perform different functionality/Operations on different/same data types当您想对不同/相同的数据类型执行不同的功能/操作时,请使用重载函数

Also, A good measure of when you really need a overloaded function over template is when you are making too many explicit specializations for a templated version of function.此外,当您对模板版本的 function 进行过多显式特化时,一个很好的衡量标准是,您何时真的需要重载 function。

In your example if you performing same operations in both the versions of the functions, You should use templates, else you should use Overloaded function.在您的示例中,如果您在两个版本的函数中执行相同的操作,您应该使用模板,否则您应该使用重载的 function。

As far as I can see a template solution would result in the same compiled object but no repetition in the source.据我所见,模板解决方案将导致相同的编译 object 但在源代码中没有重复。 A clear win for templates.模板的明显胜利。

I don't understand the point about templates needing more memory.我不明白模板需要更多 memory 的意义。 That sounds like a misthink.这听起来像是个误会。

Usually you would overload a function when you know the types that you are going to use.通常,当您知道要使用的类型时,您会重载 function。

Usually you will overload a function when there's an actual logical difference (different code) between the types you're using.通常,当您使用的类型之间存在实际的逻辑差异(不同的代码)时,您将重载 function。
And you can do that because you know the actual types and their traits.你可以这样做,因为你知道实际的类型和他们的特征。

The power of templates is that you can write the function it once, and then use the method for any type you want.模板的强大之处在于您可以将 function 编写一次,然后将方法用于您想要的任何类型。
But the template should be general enough to fit any type given to it.但是模板应该足够通用以适应给它的任何类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM