c++ - std::endl 不适用于重载的运算符<<,尽管实现了专用的非模板函数

标签 c++ operator-overloading function-pointers std endl

我有一些具有以下功能的 Logging::Logger 类:

template<typename T>
const Logger& Logger::operator<<(const T& in) const {
    // ...
    return *this;
}

const Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&)) {
    // ...
    return *this;
}

以及以下代码:

loggerInstance << "ID: " << 5 << endl;

虽然所有操作符似乎都已实现,但我收到以下错误:

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

当然,没有 endl 一切正常。

我看过以下答案:

std::endl is of unknown type when overloading operator<<

我错过了什么?

最佳答案

因为您的重载运算符返回一个 const Logger & , 因此它们必须是 const类方法,以便您能够将它们链接在一起:

const Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&)) const

但是,最好不要 const类成员,并返回一个 Logger & ,而是:

template<typename T> Logger& Logger::operator<<(const T& in)

Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&))

这大概是因为 operator<<将修改 Logger例如,以某种方式。如果没有,您可以使用 const对象和方法,在这里。

关于c++ - std::endl 不适用于重载的运算符<<,尽管实现了专用的非模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809116/

相关文章:

c++ - 未解析的外部符号 "private: static int Math::result"

c++ - 使用 GLX(opengl 和 Xlib)设置图像(jpeg | png)背景

c++ - C std::lower_bound,使用重载运算符作为二进制谓词 comp?

c++ - 在 Rectangle 类中重载运算符

c++ - 在 std::map 中打印迭代器的索引

c++ - 使用.inl内联文件的不完整向前声明

c++ - 在 C 中创建 cout 函数?

ruby-on-rails - 如何在 Ruby 中为 new 创建一个未绑定(bind)的方法

c++ - 在没有模板的情况下评估另一个类的动态函数指针

c++ - 将用户输入传递给带有 char* 参数的函数