Thursday, 21 September 2017

Class template having function template definition outside class in C++

/*
 Class template having function template definition
 Note: If you write showData() definition outside class in normal way, means without template
 then age and name wont be accessible. thats the reason showData() is defined inside.
*/
#include "iostream"
using namespace std;

template <class T1, class T2>
class Person{
 T1 age;
 T2 name;
 public:
  void getData();
  void showData(){
   cout<<"\nage: "<<age<<"\tname: "<<name<<endl;
  }
};
template <class T1, class T2> void Person<T1,T2>:: getData(){
 cin>>age>>name;
}


int main(){
 Person<int, string> ob;
 ob.getData();
 ob.showData();
 return 0;
}

/*
 OUTPUT

[pavan@Pavan ClassTemp]$ g++ ClassTemp4.cpp
[pavan@Pavan ClassTemp]$ ./a.out 
32 Pavan

age: 32 name: Pavan
[pavan@Pavan ClassTemp]$ 
 
*/

No comments: