为什么我的自定义输出流类无法工作?

22 浏览
0 Comments

为什么我的自定义输出流类无法工作?

可能是重复问题:当重载operator<<时,std::endl的类型未知\n

#include 
using namespace std;
struct OutputStream
{
    template
    OutputStream& operator <<(const T& obj)
    {
        cout << obj;
        return *this;
    }
};
OutputStream os;
int main()
{    
    os << 3.14159 << endl; // 编译错误!
}

\nVC++ 2012编译器报错:\n

错误 C2676: 二进制'<<':'OutputStream'未定义此运算符或转换为预定义运算符可接受的类型

0
0 Comments

问题的原因是编译器无法推断出T的类型,因为std::endl是一个函数模板,定义如下:

template <class charT, class traits>
  basic_ostream<charT,traits>& endl ( basic_ostream<charT,traits>& os );

在IOStreams中,通过提供适当的operator<<重载来解决这个问题:

OutputStream& operator <<(std::ostream& ( *pf )(std::ostream&))
{
  cout << pf;
  return *this;
}

很好的答案!简洁又通用!

0