2

This is a follow up question to this SO question and one of the answers.

I sometimes want to define a function in a header-only manner in a .h file, e.g.:

int id(int i) { return i; }

I know this can be done using inline functions. As I read from the comments

inline is just a hint to the compiler, it may not inline sometimes

Based on the linked answer above, it seems also possible just to

make it a template function

by e.g. using a dummy type variable in a header test.h as follows:

template <typename T = void>
int id(int i) { return i; }

and then use it in a source file below with g++ -std=c++17 test.cpp test2.cpp

#include "test.h"
int main() { return id(1); }

(test2.cpp is a copy of test.cpp with the main() function renamed to something else)

My questions are:

  1. Is the above technique with templates safe to use with respect to ODR and compilation? (In other words, is there any case in which the above technique will fail?)

  2. If so, is it possible to rewrite the template and drop the dummy template variable T (typename T = void) in order to make it shorter (i.e., zero-parametered) and less noisy?

thor
  • 21,418
  • 31
  • 87
  • 173

1 Answers1

3

inline is just a hint to the compiler, it may not inline sometimes

Though that's correct how inlined1 code is handled by the linker, the inline keyword is necessary for non templated free function definitions appearing in header files to prevent multiple definition errors at the linking phase.

In other words:
If a matching inlined1 definition of a function is seen at the linking phase inline allows to identify its source and decide to replace it with the first definition seen by the linker (actually inlined1 or not).


1)Inlined in that context means that some simple statement that would e.g. just require some simple CPU register operations, can be replaced with these, instead of emitting a complete function call frame.

user0042
  • 7,917
  • 3
  • 24
  • 39