c++c++11g++ostreamendl

Overloading endl compilation issue in GNU g++ 4.9.2


I'm having problem in compilation of the following code snippet while using GNU g++ 4.9.2 (used to compile ok in g++ 2.95.3)

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

The error is as below:

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

Please guide/help.


Solution

  • Select the overload of std::endl with a 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';
    }