C++ - vsprintf_s and std::string?
C++ - vsprintf_s and std::string?
我具有使用'...'参数的记录函数,并使用vsprintf_s
创建最终输出字符串它可以正常工作,除了我总是必须使用c_str()打印字符串
起初,我认为这不是问题,但是在每个字符串变量之后添加所有这些 .c_str()是很痛苦的,而我一直忘记它们
i虽然C 大师可以在这个问题上启发我,但是有没有办法让我的记录功能单独照顾这个?
void Logger::print(const std::string fmt, ...)
{
va_list args;
int len;
char * buffer;
va_start(args, fmt);
len = _vscprintf(fmt.c_str(), args)+1;
buffer = (char*)malloc(len * sizeof(char));
vsprintf_s(buffer, len, fmt.c_str(), args);
va_end(args);
std::cout << buffer << std::endl;
free(buffer);
}
谢谢
您可以添加两个variadic包装器功能模板:
#include <type_traits>
template <class Arg>
decltype(auto) prepare(const Arg& arg)
{
if constexpr (std::is_same_v<Arg, std::string>)
return arg.c_str();
else
return arg;
}
template <class ...Args>
void printWrapper(Args&&... args)
{
Log::print(prepare(std::forward<Args>(args))...);
}
调用printWrapper
而不是原始成员函数。请注意,我认为Log::print
在这里为静态成员函数。如果不是这种情况,则需要对其进行调整。这应该现在起作用:
const std::string hello("hello");
printWrapper("%d %s %s", 42, hello, "world");
请注意,C 17是需要编译的。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL