I am trying to get a better understanding on some advanced staffs of C++. I am trying to understand stream operator overloading
, friend function
and template
now. I am trying to learn all these things in a single code segment.
So, I am trying to implement a template class
which will just contain an array
, which I want to populate with stream operator
. So,I came up with this.
#include <iostream>
using namespace std;
template<class T, int L>
class TestClass
{
private:
T data[L];
public:
friend void operator>>(const istream&, const TestClass<T,L>&);
};
template<class T, int L>
void operator>>(const istream& in, const TestClass<T,L>& q)
{
for(int i = 0; i < L; i++)
{
in >> q.data[i];
}
}
int main() {
TestClass<float, 3> Q;
cin >> Q;
return 0;
}
This is pretty easy code segment. But, I am getting following error on compilation
undefined reference to `operator>>(std::istream const&, TestClass<float, 3> const&)'
with the following warning
warning: friend declaration 'void operator>>(const istream&, const TestClass<T, L>&)' declares a non-template function [-Wnon-template-friend]|
I know, I am doing some rookie mistake, as I am pretty new to this things. It will be great if someone helps to run this successfully.
void operator>>(const istream& in, const TestClass<T,L>& q)
-- How are you going to modifyq
if it isconst
?operator>>()
return astd::istream
(the sameit
, in your case), notvoid
istream
. is it ?cin >> an_int >> a_test_class;
works, butcin >> a_test_class >> an_int;
doesn't. That's really strange behaviour. In addition, the commonif (cin >> foo)
pattern doesn't work with your class.