开发者

C++ template and inline

开发者 https://www.devze.com 2023-01-15 15:31 出处:网络
When I\'m writing a simple (non-template) class, if the function implementation is provided \"right in place\", it\'s automatically treated as inline.

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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消