米鼠商城

多快好省,买软件就上米鼠网

最新项目

人才服务

靠谱的IT人才垂直招聘平台

第9章 在实践中使用模板:9.2 模板和内联

  • qwertt
  • 3
  • 2020-05-23 08:03

9.2 Templates and inline

9.2 模板和内联

 

Declaring functions to be inline is a common tool to improve the running time of programs. The inline specifier was meant to be a hint for the implementation that inline substitution of the function body at the point of call is preferred over the usual function call mechanism.

将函数声明为inline是提高程序性能的一种常见手段。inline修饰符是给编译器一个提示,即要优先在函数调用处用函数体作内联替换,而不是使用常规的函数调用机制。

However, an implementation may ignore the hint. Hence, the only guaranteed effect of inline is to allow a function definition to appear multiple times in a program (usually because it appears in a header file that is included in multiple places).

但是编译器可能会忽略这一提示。因此inline唯一可以保证的效果就是允许函数定义在程序中多次出现(通常是因为它定义于头文件,但被多个地方include)

Like inline functions, function templates can be defined in multiple translation units. This is usually achieved by placing the definition in a header file that is included by multiple CPP files.

与内联函数一样,可以在多个翻译单元中定义函数模板。这通常是这样来实现的:将函数模板定义在头文件,而该头文件又被多个cpp文件所包含。

This doesn’t mean, however, that function templates use inline substitutions by default. It is entirely up to the compiler whether and when inline substitution of a function template body at the point of call is preferred over the usual function call mechanism. Perhaps surprisingly, compilers are often better than programmers at estimating whether inlining a call would lead to a net performance improvement. As a result, the precise policy of a compiler with respect to inline varies from compiler to compiler, and even depends on the options selected for a specific compilation.

但这并不意味着函数模板在默认情况下就会被内联替换。在模板调用处是否首选用函数体inline替换而不使用普通函数调用,这件事完全是由编译器决定。令人惊讶的是,编译器在评估内联调用是否会导致程序净性能提高方面,编通常比程序员做得更好。因此,不同编译器之间对内联处理的精确策略是因编译器而异,甚至这依赖于特定的编译选项。

Nevertheless, with appropriate performance monitoring tools, a programmer may have better information than a compiler and may therefore wish to override compiler decisions (e.g., when tuning software for particular platforms, such as mobiles phones, or particular inputs). Sometimes this is only possible with compiler-specific attributes such as noinline or always_inline.

不过,通过合适的性能监测工具,程序员可能会比编译器更知道是否进行inline替换。同时希望由自己而不是让编译器来决定(例如,当针对移动平台或特定输入平台进行调优软件时),有时这只能使用特定于编译器的属性(如noinline或always_inline)才能做到。

It’s worth pointing out at this point that full specializations of function templates act like ordinary functions in this regard: Their definition can appear only once unless they’re defined inline (see Section 16.3 on page 338). See also Appendix A for a broader, detailed overview of this topic.

值得指出的是,在这一方面函数模板的完全特化和普通函数是一样的:除非被定义为inline,否则它只能被定义一次。关于这个主题更全面、更详细的阐述请参阅附录E。



这里给大家推荐一个在线软件复杂项交易平台:米鼠网 https://www.misuland.com

米鼠网自成立以来一直专注于从事软件项目人才招聘软件商城等,始终秉承“专业的服务,易用的产品”的经营理念,以“提供高品质的服务、满足客户的需求、携手共创双赢”为企业目标,为中国境内企业提供国际化、专业化、个性化、的软件项目解决方案,我司拥有一流的项目经理团队,具备过硬的软件项目设计和实施能力,为全国不同行业客户提供优质的产品和服务,得到了客户的广泛赞誉。

猜你喜欢

评论留言