1

我在使用 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]                 ^

请指导/帮助。

4

2 回答 2

3

std::endl用 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';
}
于 2016-06-08T11:14:48.007 回答
2

std::endl是一个函数模板,你需要指定模板参数。因为你正在使用std::ostream(ie basic_ostream<char>) 你可以

if (f == endl<char, std::char_traits<char>>)
于 2016-06-08T11:14:41.500 回答