gpt4 book ai didi

c++ - 如何实现带参数的自定义流操纵器?

转载 作者:太空宇宙 更新时间:2023-11-04 12:31:15 25 4
gpt4 key购买 nike

例如,我想要一个流操纵器,我可以将 uint8_t(unsigned char)传递给并让它输出(例如):

000fa6

我知道可以使用不带参数的流操纵器:

std::ostream &hex_format(std::ostream &out)
{
out << std::hex << std::setfill('0') << std::setw(2);
return out;
}

uint8_t x {15};
std::cout << hex_format << static_cast<int>(x); // should produce "0f"

但是我怎样才能创建一个接受参数的操纵器呢?像这样的东西:

std::ostream &hex_format(std::ostream &out, uint8_t x)
{
out << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>(x);
return out;
}

uint8_t x {15};
std::cout << hex_format(x); // (want to) produce "0f"

最佳答案

使用操纵器类:

struct hex_format {
std::uint8_t number;

hex_format(std::uint8_t x)
:number{x}
{
}
};

然后定义合适的运算符:

template <typename CharT, typename Traits>
decltype(auto) operator<<(std::basic_ostream<CharT, Traits>& os, hex_format rhs)
{
return os << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(x);
}

题外话:其实这样会全局修改流的状态,影响后面的流操作。您可以通过保存状态来解决此问题:

template <typename CharT, typename Traits>
decltype(auto) operator<<(std::basic_ostream<CharT, Traits>& os, hex_format rhs)
{
auto flags = os.flags();
os << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(x);
os.flags(flags);
return os;
}

关于c++ - 如何实现带参数的自定义流操纵器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58576178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com