Link to home
Start Free TrialLog in
Avatar of pgmerLA
pgmerLA

asked on

template and class questionc

Is there any way to write this statement without causing a compiling error? (illegal use of this type as an expression)

(line 15) {cout<<"Enter "<<n<<"data of "<<T<<" type: ";

Thanks.
#include<iostream>

using namespace std;

template<class T, int n>
class Two
{private: T a[n];
public: void Read();//read data into array a
		void Display();//display array a

};

template<class T, int n>
void Two<T ,  n>::Read()
{cout<<"Enter "<<n<<"data of "<<T<<" type: ";
for(int i= 0; i<n;++i)
	{cin>>a[i];}
}

template<class T, int n>
void Two<T,n>::Display()
{for(int i=0;i<n;++i)
{cout<<a[i]<<endl;}
}

int main()
{
Two<int,5> p;
p.Read();
p.Display();

return 0;}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
How would overloading the stream operators help?
oops. Sorry, I was looking at the wrong line.
I thought that he wanted to print the value or receive input into an instance of type T using the "<<" or ">>" operator. :)
Home now. The code below builds and does what I believe you are trying to do. My suggestion above does, indeed, work as I expected.

http://www.cppreference.com/wiki/language/typeid
http://www.cppreference.com/wiki/utility/rtti/type_info/start
#include<iostream>
#include <typeinfo>
using namespace std;

template<class T, int n>
class Two
{
private: T a[n];
public: void Read();//read data into array a
        void Display();//display array a

};

template<class T, int n>
void Two<T ,  n>::Read()
{
   cout<<"Enter "<<n<<" data of "<<typeid(T).name()<<" type: "; //< --- use typeid
   for(int i= 0; i<n;++i)
   {
      cin>>a[i];
   }
}

template<class T, int n>
void Two<T,n>::Display()
{
   for(int i=0;i<n;++i)
   {
      cout<<a[i]<<endl;
   }
}

int main()
{
   Two<int,5> p;
   p.Read();
   p.Display();

   return 0;
}

Open in new window