Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

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.

Upvotes: 1

Views: 78

Answers (2)

user2249683
user2249683

Reputation:

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

Upvotes: 3

songyuanyao
songyuanyao

Reputation: 172934

std::endl is a function template, you need to specify the template arguments. Because you're using std::ostream (i.e. basic_ostream<char>) you could

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

Upvotes: 2

Related Questions