C++ - vsprintf_s and std::string?

C++ - vsprintf_s and std::string?

本文关键字:std string and vsprintf C++      更新时间:2023-10-16

我具有使用'...'参数的记录函数,并使用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是需要编译的。