GNU g++ 4.9.2 中的重载 endl 编译问题

Overloading endl compilation issue in GNU g++ 4.9.2

我在使用 GNU g++ 4.9.2 编译以下代码片段时遇到问题(用于在 g++ 2.95.3 中编译正常)

XOStream &operator<<(ostream &(*f)(ostream &))  {
        if(f == std::endl) {
                *this << "\n" << flush;
        }
        else {
                ostr << f;
        }
        return(*this);
}

错误如下:

error: assuming cast to type 'std::basic_ostream<char>& (*)(std::basic_ostream<char>&)' from overloaded function [-fpermissive]
     [exec]    if(f == std::endl) {
     [exec]                 ^

请guide/help.

std::endl is a function template, you need to specify the template arguments. Because you're using std::ostream(即 basic_ostream<char>)你可以

if (f == endl<char, std::char_traits<char>>)

Select std::endl 的重载 static_cast:

#include <iostream>
#include <iomanip>

inline bool is_endl(std::ostream &(*f)(std::ostream &)) {
    // return (f == static_cast<std::ostream &(*)(std::ostream &)>(std::endl));
    // Even nicer (Thanks M.M)
    return (f == static_cast<decltype(f)>(std::endl));
}

int main()
{
    std::cout << std::boolalpha;
    std::cout << is_endl(std::endl) << '\n';
    std::cout << is_endl(std::flush) << '\n';
}