S
subramanian100in
consider the following program:
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <list>
using namespace std;
template<typename T> void fn(T const & arg)
{
cout << "from fn: " << sizeof(arg) << endl;
return;
}
template<typename T> void g(const vector<T>& arg)
{
cout << "from g: " << sizeof(T) << " "
<< sizeof(arg) << endl;
return;
}
int main()
{
vector<int> vi;
fn(vi);
list<string> ls;
fn(ls);
g(vi);
vector<long double> vld;
g(vld);
return EXIT_SUCCESS;
}
When fn() is called with 'vi' and 'ls', the parameter types deduced
for 'T' in fn() are 'vector<int>' and 'list<string>' respectively -
that is 'vector<int>' and 'list<string>' get substituted for 'T' in
fn(). However, when g() is called with 'vi' and 'vld', the parameter
types deduced for 'T' in g() are 'int' and 'long double' respectively
- that is, 'vector<int>' and 'vector<long double>' are NOT substituted
for 'T' in g().
I thought when g() is called with 'vi' ie 'g(vi)' would instantiate
void g(const vector< vector<int> > &arg) and when g() is called with
'vld' ie 'g(vld)' would instantiate void g(const vector< vector<long
double> > & arg). But it doesn't seem to be the case.
I am unable to understand the difference between the function template
argument deduction for fn() and g(). Kindly explain.
Thanks
V.Subramanian
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <list>
using namespace std;
template<typename T> void fn(T const & arg)
{
cout << "from fn: " << sizeof(arg) << endl;
return;
}
template<typename T> void g(const vector<T>& arg)
{
cout << "from g: " << sizeof(T) << " "
<< sizeof(arg) << endl;
return;
}
int main()
{
vector<int> vi;
fn(vi);
list<string> ls;
fn(ls);
g(vi);
vector<long double> vld;
g(vld);
return EXIT_SUCCESS;
}
When fn() is called with 'vi' and 'ls', the parameter types deduced
for 'T' in fn() are 'vector<int>' and 'list<string>' respectively -
that is 'vector<int>' and 'list<string>' get substituted for 'T' in
fn(). However, when g() is called with 'vi' and 'vld', the parameter
types deduced for 'T' in g() are 'int' and 'long double' respectively
- that is, 'vector<int>' and 'vector<long double>' are NOT substituted
for 'T' in g().
I thought when g() is called with 'vi' ie 'g(vi)' would instantiate
void g(const vector< vector<int> > &arg) and when g() is called with
'vld' ie 'g(vld)' would instantiate void g(const vector< vector<long
double> > & arg). But it doesn't seem to be the case.
I am unable to understand the difference between the function template
argument deduction for fn() and g(). Kindly explain.
Thanks
V.Subramanian