std :: endl是未知类型,当重载operator<< [英] std::endl is of unknown type when overloading operator<<

查看:218
本文介绍了std :: endl是未知类型,当重载operator<<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I overloaded operator<<

I overloaded operator <<

template <Typename T>
UIStream& operator<<(const T);

UIStream my_stream;
my_stream << 10 << " heads";

适用于:

my_stream << endl;

导致编译错误:


错误C2678:binary'< <':没有操作符,它接受类型为'UIStream'的左侧操作数(或没有可接受的转换)

error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'UIStream' (or there is no acceptable conversion)

关于 my_stream<< endl 工作?

推荐答案

std :: endl 是一个函数, std :: cout 通过实现 operator std :: endl 相同的签名。

std::endl is a function and std::cout utilizes it by implementing operator<< to take a function pointer with the same signature as std::endl.

在这里,它调用函数并转发返回值。

In there, it calls the function, and forwards the return value.

#include <iostream>

struct MyStream
{
    template <typename T>
    MyStream& operator<<(const T& x)
    {
        std::cout << x;

        return *this;
    }


    // function that takes a custom stream, and returns it
    typedef MyStream& (*MyStreamManipulator)(MyStream&);

    // take in a function with the custom signature
    MyStream& operator<<(MyStreamManipulator manip)
    {
        // call the function, and return it's value
        return manip(*this);
    }

    // define the custom endl for this stream.
    // note how it matches the `MyStreamManipulator`
    // function signature
    static MyStream& endl(MyStream& stream)
    {
        // print a new line
        std::cout << std::endl;

        // do other stuff with the stream
        // std::cout, for example, will flush the stream
        stream << "Called MyStream::endl!" << std::endl;

        return stream;
    }

    // this is the type of std::cout
    typedef std::basic_ostream<char, std::char_traits<char> > CoutType;

    // this is the function signature of std::endl
    typedef CoutType& (*StandardEndLine)(CoutType&);

    // define an operator<< to take in std::endl
    MyStream& operator<<(StandardEndLine manip)
    {
        // call the function, but we cannot return it's value
        manip(std::cout);

        return *this;
    }
};

int main(void)
{
    MyStream stream;

    stream << 10 << " faces.";
    stream << MyStream::endl;
    stream << std::endl;

    return 0;
}

希望这能让您更好地了解这些工作原理。

Hopefully this gives you a better idea of how these things work.

这篇关于std :: endl是未知类型,当重载operator&lt;&lt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆