C++ template and inline

Yippie-Ki-Yay picture Yippie-Ki-Yay · Sep 12, 2010 · Viewed 34k times · Source

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.

Answer

Johannes Schaub - litb picture Johannes Schaub - litb · Sep 12, 2010

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.