operator overload

Biotronic simen.kjaras at gmail.com
Tue Dec 12 17:13:55 UTC 2017


On Tuesday, 12 December 2017 at 16:54:17 UTC, Biotronic wrote:
> There is no way in C++ to set the format the way you want it. 
> If you want binary output, you need to call a function like 
> your binario function.

Of course this is not entirely true - there is a way, but it's 
ugly and probably not what you want:

     struct BinStream
     {
         std::ostream& os;
         BinStream(std::ostream& os) : os(os) {}

         template<class T>
         BinStream& operator<<(T&& value)
         {
             os << value;
             return *this;
         }

         BinStream& operator<<(int value)
         {
             os << binario(value);
             return *this;
         }

         std::ostream& operator<<(std::ios_base& (__cdecl 
*_Pfn)(std::ios_base&))
         {
             return os << _Pfn;
         }
     };

     struct Bin
     {
         friend BinStream operator<<(std::ostream& os, const Bin& 
f);
     } bin;

     BinStream operator<<(std::ostream& os, const Bin& f)
     {
         return BinStream(os);
     }

int main()
{
     std::cout << "\n\t127 em binario:     " << binario(127)
         << "\n\t127 em binario:     " << bin << 127
         << "\n\t127 em octal:       " << std::oct << 127
         << "\n\t127 em binario:     " << bin << 127
         << "\n\t127 em hexadecimal: " << std::hex << 127
         << "\n\t127 em binario:     " << bin << 127
         << "\n\t127 em decimal:     " << std::dec << 127
         << "\n\t127 em binario:     " << bin << 127 << "\n\n";
}

What is this black magic? Instead of overriding how std::ostream 
does formatting, Bin::Operator<< now returns a wrapper around a 
std::ostream, which special cases ints. If it gets any other 
format specifiers, it returns the ostream again, and the binary 
formatting is gone.

All in all, I think the conclusion is: Stay with D.

--
   Biotronic


More information about the Digitalmars-d-learn mailing list