- I have a template class A, and a stream operator function for A that is consequently a template function.
- I have a class B that inherit from A, specifying a type for the template and adding some stuff specific to B.
- I am writing a stream operator on B that does something specific to B and then falls back to the rest of the stream operations programmed for A.
Because B is a subclass of A (do you call it that?), invoking A’s stream operator should work. In fact, operator>>(f,a) in main() works. But for some reason it doesn’t work on b casted to A. The error I get is “no matching function for call to ‘operator>>(std::basic_istream >&, A)”.
What am I doing wrong?
Here is the sample code:
#include <stdlib.h>
#include <fstream>
#include <iostream>
using namespace std;
template <class TypeT>
class A
{
public:
A(){a = -9;}
A(TypeT v){a = v;}
TypeT a;
};
class B : public A<int>
{
public:
B(int w) : A<int>(10) {b = w;}
int b;
};
template <class TypeT>
istream &operator>> (istream &s, A<TypeT> &a)
{
cout << "a.a = " << a.a << endl;
return s;
}
istream &operator>> (istream &s, B &b)
{
cout << "b.b = " << b.b << " ";
operator>>( s, (A<int>)b); // error!
return s;
}
int main(void) {
ifstream f("/dev/null");
A<int> a(0);
operator>>( f, a );
B b(1);
operator>>( f, b );
return EXIT_SUCCESS;
}
.
Change your cast to:
Your original cast creates a temporary which you can only get a const reference to.