创建包含字符串和 std::endl 的变量,可用于 std::cout 的输出流

Create variable that contains a string and std::endl, that can be used in output streams to std::cout

使用c++17

我有一个头文件 colors.hpp 可以帮助我将彩色输出输出到标准输出:

#pragma once
#include <string>

namespace Color
{
    static const std::string yellow = "\u001b[33m";
    static const std::string green = "\u001b[32m";
    static const std::string red = "\u001b[31m";
    static const std::string end = "\u001b[0m";
}

我经常这样用:

std::cout << Color::green << "some green text " << Color::end << std::endl;

我几乎总是把 std::endl 紧跟在 Color::end 之后。我希望能够获得相同的结果(换行符 + 缓冲区刷新),但只使用一个变量 - 类似于 Color::endl.

我只能提出 string 的解决方案,据我所知,该解决方案将包含 \n 字符,但不会强制刷新到标准输出。

static const std::string endl = std::ostringstream(static_cast<std::ostringstream &&>(std::ostringstream() << Color::end << std::endl)).str();

如果我从上面的代码中删除 .str(),那么我不能这样做: std::cout << Color::endl; 因为

error: invalid operands to binary expression ('basic_ostream<char>' and 'const std::__1::basic_ostringstream<char>')

std::endl是函数(其实是函数模板),不是对象。也就是说,如果你想复制它,你还需要一个函数。

如果将此添加到 Color

template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os )
{ 
    return os << end << std::endl;
}

然后,当你使用这个时:

std::cout << Color::green << "some green text " << Color::endl;

Color::endl() 函数将被调用,然后它可以将 Color::end 插入到流中,然后 std::endl 以获得您想要的换行符和刷新行为,如中所示这个live example.