S
somenath
I am not able to understand why the following program does not compile.
#include<iostream>
using namespace std;
template <class T >
void Fun(T t)
{
static int i = t;
class Test {
public:
Test( int t1) {
cout<<"Value = "<<i<<endl;
}
};
Test tt(t);
}
int main(void)
{
Fun<int >(5);
return 0;
}
Whenever I try to compile the program I get the following error
g++ LocalClass.cpp
/tmp/ccfEKvyT.o:LocalClass.cpp
.text+0x2b): undefined reference to `i'
collect2: ld returned 1 exit status
But I am aware that local class can access the static local variable of enclosing function. The following program proves that as well.
#include<iostream>
using namespace std;
void Fun(int t)
{
static int i=t;
class Test {
public:
Test( int t1) {
cout<<"Value = "<<i<<endl;
}
};
Test tt(t);
}
int main(void)
{
Fun(5);
return 0;
}
This code compile fine. Then what is going wrong with template version of the program?
#include<iostream>
using namespace std;
template <class T >
void Fun(T t)
{
static int i = t;
class Test {
public:
Test( int t1) {
cout<<"Value = "<<i<<endl;
}
};
Test tt(t);
}
int main(void)
{
Fun<int >(5);
return 0;
}
Whenever I try to compile the program I get the following error
g++ LocalClass.cpp
/tmp/ccfEKvyT.o:LocalClass.cpp
collect2: ld returned 1 exit status
But I am aware that local class can access the static local variable of enclosing function. The following program proves that as well.
#include<iostream>
using namespace std;
void Fun(int t)
{
static int i=t;
class Test {
public:
Test( int t1) {
cout<<"Value = "<<i<<endl;
}
};
Test tt(t);
}
int main(void)
{
Fun(5);
return 0;
}
This code compile fine. Then what is going wrong with template version of the program?