用于将数据类型打印到调试控制台的函数

Function to print data type to debug console

本文关键字:控制台 函数 调试 数据类型 打印 用于      更新时间:2024-09-23

在中搜索任何类型的函数都可以帮助将数据打印到调试控制台,但我在StackOverflow上发现了这个函数,它几乎可以打印任何类型的数据:

template <typename Arg, typename... Args>
void doPrint(Arg&& arg, Args&&... args)
{
std::stringstream out;
out << std::forward<Arg>(arg);
using expander = int[];
(void)expander {
0, (void(out << std::left << std::setw(20) << std::forward<Args>(args)), 0)...
};
OutputDebugStringA(out.str().c_str());
}

但当我试图将wstring传递给它时,它不起作用,例如:

std::wstring color = L"blue";
doPrint("color: ", color);

我得到这个错误:

Error    C2679    binary '<<': no operator found which takes a right-hand operand of type 'std::wstring' (or there is no acceptable conversion)

是否也可以支持wstring

我试图将std::stringstream更改为std::wstringstream,但现在在OutputDebugStringA():上出现错误

void OutputDebugStringA(LPCSTR)': cannot convert argument 1 from 'std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>' to 'LPCSTR'

默认情况下,您不能将std::wstring打印到基于charstd::ostream,如std::stringstream,因为std::basic_ostream<char>(也称为std::ostream(没有为std::wstring(或const wchar_t*(定义过载的operator<<

您可以为此定义自己的operator<<,它使用WideCharToMultiByte()或等效转换将std::wstring转换为std::string/char*,然后打印,例如:

std::ostream& operator<<(std::ostream &os, const std::wstring &wstr)
{
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), nullptr, 0, nullptr, nullptr);
if (len > 0) {
std::string str;
str.resize(len);
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), str.data()/* or: &str[0] */, len, nullptr, nullptr);
os << str;
}
return os;
}
template <typename Arg, typename... Args>
void doPrint(Arg&& arg, Args&&... args)
{
std::stringstream out;
out << std::forward<Arg>(arg);
using expander = int[];
(void)expander {
0, (void(out << std::left << std::setw(20) << std::forward<Args>(args)), 0)...
};
OutputDebugStringA(out.str().c_str());
}

在线演示

否则,您需要一个基于wchar_tstd::basic_ostream<wchar_t>(也称为std::wostream(,例如std::wstringstream,使用OutputDebugStringW()进行日志记录(除非您将输出std::wstring转换为std::string以使用OutputDebugStringA()进行日志记录(。幸运的是,无论CharTchar还是wchar_tstd::basic_ostream<CharT>都有一个重载的operator<<用于const char*字符串(而不是std::string(,因此std::wstringstream可以打印std::string::c_str()返回的指针,例如:

std::wostream& operator<<(std::wostream &os, const std::string &str)
{
os << str.c_str();
return os;
}
template <typename Arg, typename... Args>
void doPrint(Arg&& arg, Args&&... args)
{
std::wostringstream out;
out << std::forward<Arg>(arg);
using expander = int[];
(void)expander {
0, (void(out << std::left << std::setw(20) << std::forward<Args>(args)), 0)...
};
OutputDebugStringW(out.str().c_str());
}

在线演示