C ++:vsprintf

问题描述

我有一个比较大的代码库,可以执行log_msg("Here comes %s","the text"),其中log_message一个宏,可以在日志消息中添加函数名和行号。

GCC / G ++在格式字符串与提供的参数不匹配时警告错误。不幸的是,有时代码调用log_msg(get_the_text())get_the_text()的返回值在编译时是未知的,因此,如果它包含一些printf格式化序列,则代码将平放在其表面。

我正在寻找的是一种通过不解释格式代码的不同代码路径来路由单个参数用法方法。我尝试过这种方法,希望非变异性案例比变异性案例更具体:

void log_the_message_implementation(const char *filename,const char *funcname,const char *msg);
void log_the_message_implementation(const char *filename,const char *msg,...);

我希望编译器在没有变量args的情况下选择单参数函数,但它抱怨调用不明确。

任何解决此问题的方法,而无需更改成千上万的呼叫 log_msg(get_the_text())log_msg("%s",get_the_text())

解决方法

感谢@SamVarshavchik,这是我想出的:

#include <iostream>
#include <cstdio>
#include <tuple>


template<typename ... Args>
void log(Args ... args) {
    if (sizeof...(args) == 1) {
        auto t = std::make_tuple(args...);
        std::puts(std::get<0>(t));
    } else {
        std::printf(args...);
    }
}

int
main() {
    log("Test %d");
    log("%s %d\n","Test",1);
    log([]{ return "%s";}());
    return 0;
}