operator overload

dark777 jeanzonta777 at yahoo.com.br
Tue Dec 12 19:00:45 UTC 2017


On Tuesday, 12 December 2017 at 17:13:55 UTC, Biotronic wrote:
> 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

I tried to execute with this part of the code

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

and it returns me this error below what is the include?

bin2.cxx:44:43: error: expected ‘,’ or ‘...’ before ‘(’ token
    std::ostream& operator<<(std::ios_base& (__cdecl 
*_Pfn)(std::ios_base&))
                                            ^
bin2.cxx: In member function ‘std::ostream& 
BinStream::operator<<(std::ios_base&)’:
bin2.cxx:46:16: error: ‘_Pfn’ was not declared in this scope
     return os <<_Pfn;


More information about the Digitalmars-d-learn mailing list