cout uint8_t as integers instead of chars

前端 未结 1 1499
南方客
南方客 2021-01-07 09:47
#include
#include
using namespace std;

int main()
{
    cout << (uint8_t)123 << endl;
}

This will out

1条回答
  •  萌比男神i
    2021-01-07 10:35

    I definitely do not condone the solution I am about to suggest. I also suspect that it may not be permitted by the standard, but I cannot prove it, as of yet. If someone can provide me a reference that shows that it is not permitted, then I will delete this answer. Anyway, my tests so far indicate that simply overloading the operator in the global scope seems to work.

    #include 
    #include 
    
    std::ostream & operator<<(std::ostream & os, std::uint8_t val)
    {
        return os << static_cast(val);
    }
    
    int main()
    {
        std::uint8_t val = 123;
        std::cout << val;
    }
    

    I wouldn't have thought this would work, but then I realized that the char/unsigned char/signed char overloads for operator<< are all free functions in the std namespace picked up by ADL. And I guess global functions are considered a better match than ADL functions, but I'm not sure about that.

    0 讨论(0)
提交回复
热议问题