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:
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?)
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?