C++ 自定义流实用程序

C++ 自定义流实用程序,c++,windows,cout,C++,Windows,Cout,我正在尝试创建一个打印实用程序,但需要一些编码方面的帮助 为了简化这个问题,我们将有一个示例实用程序。此示例实用程序将更改当前分配的windows控制台输出颜色。该实用程序将在打印语句中自动执行此操作,而不是执行SetConsoleTextAttribute(blahblahblah) e、 g: 像 std::cout << SetPrintColorTo5B << "Colored Text" << std::endl; 因此,它可以像这样使用: std

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

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

e、 g:

std::cout << SetPrintColorTo5B << "Colored Text" << std::endl;
因此,它可以像这样使用:

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

std::cout我已经有了另一种解决方案,但它不如函数格式更可取:/

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;
}
struct SetPrintColor
{
单词m_wDesiredAttribute;
SetPrintColor(单词wDesiredAttribute):m_wDesiredAttribute(wDesiredAttribute)
{ };
};

模板std::basic\u ostream<\u Elem,\u Traits>和operator这种工作方式也由标准库完成,以配置数字是否需要以十进制或十六进制打印

简而言之,您需要一个不同类型的实例来执行此操作。例如:

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

std::ostream& operator<<(std::ostream& stream, MyOwnTag)
{
     // Do some code
     return stream;
 }
struct MyOwnTag{};
constexpr静态MyOwnTag名称{};

std::ostream&operator请尝试了解当前和现有流操纵器的工作方式,这类似于
中的“函数”<代码>我不知道什么时候会回到旧的行为,std::hex也不知道。
这就是问题所在;我不确定它是否会将行为恢复到正常状态,而且我知道对于std::hex它不会这样做-您必须使用std::dec将其更改回正常状态。
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;
}
struct MyOwnTag{};
constexpr static MyOwnTag Name{};

std::ostream& operator<<(std::ostream& stream, MyOwnTag)
{
     // Do some code
     return stream;
 }
std::cout << Name << "text" << std::endl;