Since templates are defined within headers and compiler is able to determine if inlining a function is advantageous, does it make any sense? I've heard that modern compilers know better when to inline a function and are ignoring inline
hint.
edit: I would like to accept both answers, but this is not possible. To close the issue I am accepting phresnel's answer, because it received most votes and he is formally right, but as I mentioned in comments I consider Puppy's and Component 10's answers as correct ones too, from different point of view.
The problem is in C++ semantics, which is not strict in case of inline
keyword and inlining. phresnel says "write inline if you mean it", but what is actually meant by inline
is not clear as it evolved from its original meaning to a directive that "stops compilers bitching about ODR violations" as Puppy says.
As you suggested,
inline
is a hint to the compiler and nothing more. It can choose to ignore it or, indeed, to inline functions not marked inline.Using
inline
with templates used to be a (poor) way of getting round the issue that each compilation unit would create a separate object for the same templated class which would then cause duplication issues at link time. By usinginline
(I think) the name mangling works out different which gets round the name clash at link time but at the expense of vastly bloated code.Marshall Cline explains it here better than I can.
It is not irrelevant. And no, not every function template is
inline
by default. The standard is even explicit about it in Explicit specialization ([temp.expl.spec])Have the following:
a.cc
b.cc
tpl.h (taken from Explicit Specialization):
Compile this, et voila:
Not stating
inline
when doing explicit instantiation may also lead to issues.So in summary: For non fully specialized function templates, i.e. ones that carry at least one unknown type, you can omit
inline
, and not receive errors, but still they are notinline
. For full specializations, i.e. ones that use only known types, you cannot omit it.Proposed rule of thumb: Write
inline
if you mean it and just be consistent. It makes you think less about whether to or not to just because you can. (This rule of thumb is conforming to Vandevoorde's/Josuttis's C++ Template: The Complete Guide).It's irrelevant. All templates are already
inline
- not to mention that as of 2012, the only use of theinline
keyword is to stop compilers bitching about ODR violations. You are absolutely correct- your current-generation compiler will know what to inline on it's own and can probably do so even between translation units.