Hello I have this program:
I want to create a generic class Add that works as a functor, I intend to overload the stream I/O operators to works with it.
The thing is that I want the stream operators << >> to be generic too, so that there stream parameter can be an std::istream or std::ifstream and so on. This applies to the insertion operator too.
The reason I do this is that if I write std::cout << Add<int>{} will prints it on the screen and if I do: ofstream("data.txt") >> Add<int>{}; will write it to the file.
I know an
ifstreamis anistreambut I intend to use maybe other types that has their I/O operators doing another stuff.template <typename T> class Add { T operator()(T const& a, T const& b){return a + b;} template <typename STREAM_IN> friend STREAM_IN& operator >> (STREAM_IN& in, Add<T>& a){ in >> a.x; return in;} template <typename STREAM_OUT> friend STREAM_OUT& operator << (STREAM_OUT& out, Add<T> const& a){ out << a.x; return out;} int x = 89; }; //template <typename T> //template <typename STREAM_IN> //STREAM_IN& operator >> (STREAM_IN& in, Add<T>& a) //{ // return in >> a.x; //} int main() { Add<long> a; std::ifstream in("data.txt"); in >> a; std::cout << a << '\n'; in.close(); a.x += 7; std::ofstream out("data.txt"); out << a; std::cout << "\ndone!\n"; }The problem: How can I defined
>>and<<outside the template class body?