Re: How many times will a template function be instantiated for the
same parameter?
On May 28, 5:41 am, Shriramana Sharma wrote:
# include <vector>
using namespace std;
template <typename T>
vector<T>& operator<<(vector<T> & vec, const T & val)
{ vec.push_back(val) ; return vec ; }
Don't put "using namespace std;" in a header file.
This is so I can do something like:
vector<int> A ;
A << 1 << 2 << 3 ;
My question is how often will this function be instantiated? I mean,
if I had written it like:
vector<int>& operator<<(vector<int> & vec, const int & val)
{ vec.push_back(val) ; return vec ; }
then there would be only one definition and this function would be
called each time I use the operator. However I'm using a template
to be able to use this for a vector of any value type. So I would
like to know, how many times would a particular template be
instantiated? Would it also be one in accordance with the ODR or
something?
The ODR says that you shall only provide one definition of anything
within the same translation unit and you shall only provide one
definition within a program (consinsting of possibly multiple
translation units) for non-inline, non-template functions.
So, if you put your non-template into a .cpp file and only its
declaration in a header you'll be fine.
So, if you put your function template into a header file so that you
can use it everywhere, you'll be fine.
In practice it works like this: When you compile a translation unit
and make use of a function template in there somewhere, the compiler
will check whether it already instantiated this function template with
the same template parameters during the compilation of the translation
unit. If it did not, it will instantiate it. If yes, there is no need.
This might result in multiple definitions among different translation
units. You would get a couple of object files where more than one
contains the same code of a function template instantiation. But it's
stored with a special flag to make the linker shut up about it and
just use a single definition and ignore the duplicates. This is just a
possible implementation, not mandated by the C++ ISO standard.
Keep in mind that if you make use of a funciton template in some
translation unit, you better have its definition available in the same
translation unit (just like for inline functions). Otherwise you'll
get linker errors about missing definitions because the compiler won't
remember that it needs some certain instantiation and later go about
instantiating it when it finds the template's definition someplace
else.
Cheers!
SG