I believe that there are 4 situations where my question may have different answers. These situations are sorted by member vs. non-member functions and within vs. without a library.
Non-member function within a library
Suppose that I have defined a template function func
in header func.h
.
// func.h
template <typename T>
int func(T t){
//definition
}
I #include "func.h"
in two cpp
files of the same project/library/executable and call
//a.cpp
#include "func.h"
//stuff
int m = func<int>(3);
//stuff
and
//b.cpp
#include "func.h"
//stuff
int n = func<int>(27);
//stuff
My understanding is that these two cpp
files should compile into their own object files. In what object file is func<int>
instantiated? Why will the One Definition Rule not be violated? For this basic application of templates, is there any benefit to explicitly instantiating func<int>
separate from its use?
Member function within a library
Suppose that func
is instead a member function of some class Func
.
// func.h
class Func {
template <typename T>
int func(T t){
//definition
}
};
Where will func
be instantiated? Will func<int>
be linked to or placed inline?
Member and Non-Member functions across libraries
Suppose that a.cpp
and b.cpp
are in different libraries that are compiled separately and later linked into an executable. Will the different libraries their own definitions of func<int>
? At link time, why will the One Definition Rule not be violated?
Note: There is a related question of the same title here, but in a specific situation with one cpp
file.