gpt4 book ai didi

c++ - 重载 operator<< 时 std::endl 的类型未知

转载 作者:IT老高 更新时间:2023-10-28 13:23:32 25 4
gpt4 key购买 nike

我重载了运算符<<

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

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

有效但:

my_stream << endl;

给出编译错误:

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 具有相同签名的函数指针.

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

这是一个代码示例:

#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;
}

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

关于c++ - 重载 operator<< 时 std::endl 的类型未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1134388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com