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 <iostream>
#include <cstdint>
std::ostream & operator<<(std::ostream & os, std::uint8_t val)
{
return os << static_cast<int>(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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…