自定义流工具

时间:2018-06-19 06:23:23

标签: c++ windows cout

我正在尝试创建一个打印实用程序,但需要一些编码帮助

为了使这个问题变得简单,我们将有一个示例实用程序。此示例实用程序将更改当前分配的Windows控制台输出颜色。该实用程序不会执行SetConsoleTextAttribute( blahblahblah ),而是自动执行此操作,并在打印语句中执行此操作。

e.g:

std::ostream &SetPrintColorTo5B( std::ostream & stream )
{
    SetConsoleTextAttribute( GetStdHandle( STD_INPUT_HANDLE ), 0x5B );
    return stream;
}

一样使用
std::cout << SetPrintColorTo5B << "Colored Text" << std::endl;

现在,我如何让这个示例函数接受参数而不会弄乱整个流?

e.g:

std::ostream &SetPrintColor( std::ostream & stream, WORD wDesiredAttribute )
{
    SetConsoleTextAttribute( GetStdHandle( STD_INPUT_HANDLE ), wDesiredAttribute );
    return stream;
}

以便可以像这样使用:

std::cout << SetPrintColor << /* only this part is the parameter, and this shouldn't disrupt the stream after it */ 0x5B << "Colored Text" << std::endl;

谢谢!

2 个答案:

答案 0 :(得分:1)

我已经有了另一种解决方案,但它不如功能格式更优选:/

struct SetPrintColor
{
    WORD m_wDesiredAttribute ;
    SetPrintColor( WORD wDesiredAttribute ): m_wDesiredAttribute( wDesiredAttribute )
    { };
};

template < typename _Elem, typename _Traits > std::basic_ostream< _Elem, _Traits > &operator<<( std::basic_ostream< _Elem, _Traits > &stream, SetPrintColor& clr )
{
    SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), clr.m_wDesiredAttribute );
    return stream;
}

它将像std::cout << SetPrintColor( 0x5B ) << "Colored text" << std::endl;

一样使用

答案 1 :(得分:0)

这种工作方式也由标准库完成,用于配置是否需要以十进制或十六进制数字打印数字。

简而言之,您需要一个不同类型的实例才能这样做。例如:

struct MyOwnTag{};
constexpr static MyOwnTag Name{};

std::ostream& operator<<(std::ostream& stream, MyOwnTag)
{
     // Do some code
     return stream;
 }

如果要在多个流上重用代码,可以将其模板化,或者将逻辑放在类中并从流操作符中调用它。

std::cout << Name << "text" << std::endl;

我不知道这会回到原来的行为,也不会回到std::hex

如果你想以某种方式强行重置一下。我建议将返回的流包装到析构函数执行重置逻辑的类中。请务必考虑复制/移动构造函数和临时构造函数。