Re: template function instantiation
George wrote:
[..]
Why the following code will only instantise function f with parameter
int, not double?
It will not instantiate anything since the code does not define 'g'
at the point of first use. If you move the definition of 'g' function
above the template, it should instantiate both.
Because extern g(double) is declared local, not
global? As the following statement from Bjarne said,
--------------------
That point is the nearest global or namespace scope enclosing its use,
just before the declaration that contains that use.
--------------------
[Code]
#include <iostream>
using namespace std;
template <class T> void f(T a) {g (a);}
This should not compile at all. 'g' is undefined here.
void g (int a)
{
cout << a << endl;
}
int main()
{
extern void g (double);
I am not certain, but this declaration _may_be_ hiding the
declaration in the global namespace.
f (100);
f (2.0); // will call int version f, not double version f
The comment is incorrect - it will call the 'double' version.
return 0;
}
[/Code]
It's curious how the absence of 'g(double)' from linking affected
the outcome with Visual C++. This code (valid, compiled with VC++
2005):
--------------------
#include <iostream>
using namespace std;
void g (int a)
{
cout << "int " << a << endl;
}
template <class T> void f(T a) {g (a);}
int main()
{
void g (double);
f (100);
f (2.0);
return 0;
}
--------------------
has the output
int 100
int 2
And if you add g(double) at the end:
--------------------
#include <iostream>
using namespace std;
void g (int a)
{
cout << "int " << a << endl;
}
template <class T> void f(T a) {g (a);}
int main()
{
void g (double);
f (100);
f (2.0);
return 0;
}
void g(double a)
{
cout << "double " << a << endl;
}
----------------
, the output becomes
int 100
double 2
----------------
VC++ 2005 is still not up to snuff WRT templates, AFAICT.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask