gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:39:09 26 4
gpt4 key购买 nike

使用 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 所示.

关于c++ - 创建包含字符串和 std::endl 的变量,可用于 std::cout 的输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69105158/

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