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 understand is basically this now I will see the necessity of this basically the example I wanted to do is to understand how it would be done in the most correct way, now I will study to do other cases if nescessarios but primarily is to convert only integers but you did exactly the that I wanted

I did some studies in the D language and it already has a way to convert to binary without any work just using% b as in printf you use% X or% x to convert to exa ... and that was the reason that made me interested in understand this was looking at some older glibc and the way printf understands these very interesting conversion operators

Reply via email to