我会说主要函数模板和 重载函数之间的区别在于编译器在 $中寻找函数调用的匹配时会区分 函数模板b $ b源代码。如果可以,编译器将更喜欢调用 重载函数,而不必为源代码中出现的任何函数调用实例化一个函数 模板。 这种偏见的后果很有意思。特别令人惊讶的是 很多是专门的功能模板不考虑 匹配,除非它专门化的功能模板首先确定 成为所有候选功能的最佳匹配。这个策略的含义是,C ++编译器不会调用 专用模板函数 - 即使它的声明是完全的 匹配对于源代码中的函数调用 - 如果甚至有一个 函数重载,编译器认为比具有完全匹配的特殊化的 函数模板更好地匹配。好吧, 这是一口! 当然,人们可能会期望专门化 功能模板的原因每当源代码中的 函数调用使用完全匹配其专有类型的参数时,确保调用它。事实上,它是如何工作的 - 对于 重载函数(通常是一个重载函数是 开发人员真正想在这里写的。) 专门的函数模板不能确保函数匹配 调用。相反,专门的版本只告诉编译器如何为其特定的参数类型实例化函数模板, 它应该专门的函数模板是否是 a函数调用源代码。 格雷格 [见 http://www.gotw.ca/resources/clcm.htm 有关的信息] [ comp.lang.c ++。主持。第一次海报:做到这一点! ]I would say the "major" difference between a function template and anoverloaded function is that the compiler discriminates against afunction template whenever it seeks a match for a function call in thesource code. When it can, the compiler will prefer to call anoverloaded function instead of having to instantiate a functiontemplate for any function call appearing in source code.The consequences of this bias are interesting. Especially surprising tomany is that a specialized function template is not considered for amatch, unless the function template it specializes is first determinedto be the best match of all available candidate functions. Theimplication of this policy is that the C++ compiler will not call aspecialized template function - even if its declaration is an exactmatch for the function call in the source code - if there is even onefunction overload that the compiler deems a better match than thefunction template with the specialization that matches exactly. Well,that was a mouthful!Of course, one might expect that the reason for specializing thefunction template would be to ensure that it gets called whenever afunction call in the source code uses parameters that match itsspecialized types exactly. And in fact, that is how it works - foroverloaded functions (and usually an overloaded function is what thedeveloper really wanted to write here.)A specialized function template is not to ensure a match for a functioncall. Rather the specialized version merely tells the compiler how toinstantiate the function template for its particular parameter types,should the function template it specializes ever be the best match fora function call in the source code.Greg[ See http://www.gotw.ca/resources/clcm.htm for info about ][ comp.lang.c++.moderated. First time posters: Do this! ] 这篇关于使用函数重载和函数模板之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-24 20:58