Search code examples
c++ostreamiomanip

How to test for std::showbase or std::noshowbase in output operator?


I have a big integer class, and I'm trying to make it honor std::showbase and std::noshowbase. Here, "honor" means to control the use of a suffix as defined in the Integer class (and not the C++ standard behaviors):

std::ostream& operator<<(std::ostream& out, const Integer &a)
{
    ...

    if(out.flags() & std::noshowbase)
        return out;

    return out << suffix;
}

However, it results in an error:

$ make static
c++ -DDEBUG -g3 -O1 -fPIC -Wno-tautological-compare -Wno-unused-value -DCRYPTOPP_DISABLE_ASM -pipe -c integer.cpp

integer.cpp:3487:17: error: invalid operands to binary expression ('int' and
      'std::ios_base &(*)(std::ios_base &)')
        if(out.flags() & std::noshowbase)
           ~~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~
/usr/include/c++/4.2.1/bits/ios_base.h:79:3: note: candidate function not
      viable: no known conversion from 'std::ios_base &(std::ios_base &)' to
      'std::_Ios_Fmtflags' for 2nd argument
  operator&(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
  ^
1 error generated.

I've also tried std::ios::noshowbase and std::ios_base::noshowbase with similar errors.

How does one test for showbase and noshowbase?


Solution

  • noshowbase is a function, not an integral of bitmask type. There's also no ios_base::noshowbase. But there is ios_base::showbase. Maybe you wanted:

    if (out.flags() & std::ios_base::showbase) {
        return out << suffix;
    }
    
    return out;