Wrong overload selected for stream manipulator

2019-06-02 10:13发布

问题:

Here's the code:

#include <iostream>
#include <iomanip>
#include <typeinfo>

#if 0
std::ostream &foo(std::ostream &os, std::ios_base &(*x)(std::ios_base &), bool show_id = false)
{ 
    if ( show_id )
        os << "(" << typeid(x).name() << ") ";
    return os << x;
}
#endif

template<typename T>
std::ostream &foo(std::ostream &os, T const &t, bool show_id = false)
{
    if ( show_id )
        os << "(" << typeid(t).name() << ") ";

    return os << t;
}

int main()
{
    foo(std::cout, std::hex) << 255 << std::endl;
    foo(std::cout, ".") << std::hex << 255 << std::dec << std::endl;

    foo(std::cout, std::hex, true) << 255 << std::endl;
}

Using bcc32 6.70 and bcc32 5.82, the output is

401358255
.ff
(std::ios_base & (*)(std::ios_base &) const) 401368255

Using bcc64 6.70 (based on clang) and g++ 4.8.2, the output is

ff
.ff
(FRSt8ios_baseS0_E) ff

I presume clang and gcc are correct, because they have better reputations than bcc32.

If I enable the commented-out function, then bcc32 outputs:

ff
.ff
(std::ios_base & (*)(std::ios_base &)) ff

What exactly is going wrong with the first version? It's presumably a compiler bug to do with overload resolution, but I can't figure out what bcc32 is doing, or what the const is on the end of the typeid output.