views:

123

answers:

3

Hello!

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> B::DontKnowFunction() { T a = 0; }

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

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

Thank you.

+2  A: 

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.

RC
I know that `inline` keyword acts as a recommendation, but in the first example (when you write code right inside of the class definition) the `inline` is "automatically prepended", so it means that at least I give this recommendation to the compiler. But I don't know what would happen in template-based cases. I'm pretty sure there are some rules for that...
HardCoder1986
Right, but whether the inline is there or not explicitly or implicitly, the compiler can do with it what it will thus you can't pre-determine the compilers behavior.
RC
+1  A: 

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.

DeadMG
Compilers are _not_ allowed to ignore the `inline` qualifier and I don't know of any modern compilers that do. `inline` makes specific well-defined changes to the language rules for multiple definitions of functions. It's not just a hint.
Charles Bailey
inline is a very specific and define meaning. But it has very little to do with "Code in-lining" and most modern compilers ignore it in regards to the `hint` it gives for "code in-lining". It terms of linking and other stuff it can not be ignored.
Martin York
+1  A: 

Since when you instantiate you get a class, that function is like an ordinary member function. It's declared 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.

Johannes Schaub - litb