【发布时间】:2021-02-12 09:22:10
【问题描述】:
你好,我有这个程序:
我想创建一个泛型类 Add 作为仿函数,我打算重载流 I/O 运算符以使用它。
问题是我希望流操作符<< >> 也是通用的,因此流参数可以是std::istream 或std::ifstream 等等。这也适用于插入运算符。
我这样做的原因是,如果我写 std::cout << Add<int>{} 会将其打印在屏幕上,如果我这样做:ofstream("data.txt") >> Add<int>{}; 会将其写入文件。
-
我知道
ifstream是istream,但我打算使用其他类型,它们的 I/O 操作符在做其他事情。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"; } -
问题:如何在模板类主体之外定义
>>和<<?
【问题讨论】:
标签: c++ templates friend-function