[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 222
  • Last Modified:

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

0
pgmerLA
Asked:
pgmerLA
  • 3
  • 2
1 Solution
 
evilrixSenior Software Engineer (Avast)Commented:
Try

cout<<"Enter "<<n<<"data of "<< typeid(T).name() <<" type: ";
0
 
UltraDogCommented:
You'll have to overload the stream operators.
http://www.java2s.com/Code/Cpp/Overload/Overloadstreamoperator.htm
0
 
evilrixSenior Software Engineer (Avast)Commented:
How would overloading the stream operators help?
0
 
UltraDogCommented:
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. :)
0
 
evilrixSenior Software Engineer (Avast)Commented:
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

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now