Reputation: 18068
I got a template class and once it gets a string
as a T
and the other Para*
as a T
.
I have overloaded <<
for Para
.
friend ostream& operator<< (ostream &wyjscie, Para const& ex){
wyjscie << "(" << ex.wrt << ", " << ex.liczbaWystapien <<")"<< endl;
return wyjscie;
}
so to print it I have to use cout<<*objectOfClassPara<<endl;
otherwise I will print
address but I can't do it for string
.
How to correct this code udner?
T t = n->key;
//cout<<n->key<<endl;
cout<<t<<endl;
if (is_same<T, Para*>::value){
cout<<*t<<endl; //IILEGAL INDIRECTION
}
Upvotes: 1
Views: 1259
Reputation: 96301
Your problem is that if
is a runtime if check, and all possible types have to compile, regardless of whether the code could actually ever execute. So when T
is string
, the *
causes the code to fail.
The simplest solution is to provide an overloaded operator<<
that works with pointers and remove the *
:
ostream& operator<< (ostream &wyjscie, Para const* ex)
{
return wyjscie << *ex;
}
Upvotes: 2
Reputation: 18848
T t
Is not a pointer, as 0x499602D2 mentions..
T* t
Is a pointer, and can be dereferenced like cout<<*t<<endl;
Template parameters need to be types, and a pointer-to-type is not valid.
Upvotes: 1