且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以整数而不是char的形式输出uint8_t

更新时间:2023-09-29 08:44:40

我绝对不容忍我要提出的解决方案.我还怀疑该标准可能不允许使用它,但是到目前为止我还不能证明它.如果有人可以向我提供表明不允许的参考,那么我将删除此答案.无论如何,到目前为止,我的测试表明,简单地在全局范围内重载运算符似乎是可行的.

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;
}

我本来以为这行不通,但是后来我意识到 operator<< char/unsigned char/signed char 重载都是***函数在ADL选取的 std 名称空间中.而且我认为全局函数比ADL函数更匹配,但是我不确定.

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.