Created a template function C++ template <class T> void myswap(T&d,T&s)
.
Main uses it for int, double, complex types.
Compiled the source using g++.
On dumping the symbol table via nm, the functions generated for the respective types have symbol type "W".
Why are they generated as weak symbols?
#include <iostream>
#include <complex>
template <class T>
void myswap(T& d, T& s)
{
T temp = d;
d=s;
s=temp;
}
int main(void)
{
int m=5,n=6;
std::cout << "m=" << m << " n=" << n <<std::endl;
myswap(m,n);
std::cout << "m=" << m << " n=" << n <<std::endl;
double p=4.3,q=5.6;
std::cout << "p=" << p << " q=" << q <<std::endl;
myswap(p,q);
std::cout << "p=" << p << " q=" << q <<std::endl;
std::complex<double> r(2.3,5.7), s(1.2,3.4);
std::cout << "p=" << r << " q=" << s <<std::endl;
myswap(r,s);
std::cout << "p=" << r << " q=" << s <<std::endl;
return 0;
}
Function template specializations that are generated by implicit instantiation are similar to inline functions in that if multiple translation units generate the same instantiation, the ODR is not violated. If this were not so, then templates would be almost unusable.
Weak linkage is the mechanism used to make this possible in a typical implementation.