C++ template and inline

眉间皱痕 提交于 2019-11-26 18:17:06

问题


When I'm writing a simple (non-template) class, if the function implementation is provided "right in place", it's automatically treated as inline.

class A {
   void InlinedFunction() { int a = 0; }
   // ^^^^ the same as 'inline void InlinedFunction'
}

What about this rule when talking about template-based classes?

template <typename T> class B {
   void DontKnowFunction() { T a = 0; }
   // Will this function be treated as inline when the compiler
   // instantiates the template?
};

Also, how is the inline rule applied to non-nested template functions, like

template <typename T> void B::DontKnowFunction() { T a = 0; }

template <typename T> inline void B::DontKnowFunction() { T a = 0; }

What would happen in the first and in the second case here?

Thank you.


回答1:


Templated functions as far as I know are automatically inline. However, the reality is that most modern compilers regularly ignore the inline qualifier. The compiler's optimizing heuristics will most likely do a far better job of choosing which functions to inline than a human programmer.




回答2:


Since when you instantiate you get a class, that function is like an ordinary member function. It's defined in that class, so the function is automatically inline.

But it does not really matter here that much. You can define function templates or members of class templates multiple times in a program anyway - you don't need inline to tell the compiler about that like in the non-template case.




回答3:


The inline keyword is not a "rule". It is merely a suggestion/hint to the compiler and what it does with it is completely up to it and it's implementation. With this in mind, it's not possible to know what will happen with your examples. The compiler may in fact inline all, some, or none of them.



来源:https://stackoverflow.com/questions/3694899/c-template-and-inline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!