实际开发中不定参数在格式化字符串中使用很常见,本篇博客关于其使用做个简单举例说明:
代码1:
#include <cstdarg>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <string.h>
void myprint(int level,
const char* module,
const char* file,
int line,
const char* function,
const char* format,
...) {
int buff_size = 1024;
int offset = 0;
char buffer[buff_size + 1] = {0};
int temp_size = 0;
struct timeval tv = { 0 };
gettimeofday(&tv, NULL);
struct tm timeinfo = { 0 };
localtime_r(&tv.tv_sec, &timeinfo);
const char* p = nullptr;
if (file != nullptr)
{
p = strrchr(file, '/');
}
temp_size = snprintf(buffer + offset, buff_size - offset - 1,
"%s:%d:%s:%s%c[%02d-%02d %02d:%02d:%02d:%03d] ",
module == NULL ? "MODULE" : module,
line,
p == nullptr ? file : (p + 1),
function == NULL ? "FUNC" : function,
' ',
timeinfo.tm_mon + 1,
timeinfo.tm_mday,
timeinfo.tm_hour,
timeinfo.tm_min,
timeinfo.tm_sec,
(int)tv.tv_usec / 1000);
if (temp_size > 0) {
offset += temp_size;
}
va_list args;
va_start(args, format);
temp_size = vsnprintf(buffer + offset, 1024 - offset, format, args);
va_end(args);
std::cout << buffer << std::endl;
}
// __VA_ARGS__可以使用##__VA_ARGS__代替
#define print1_v(module, format, ...) \
myprint(0, module, __FILE__, __LINE__, __func__, format, __VA_ARGS__)
#define print1_d(module, format, ...) \
myprint(1, module, __FILE__, __LINE__, __func__, format, __VA_ARGS__)
#define print1_i(module, format, ...) \
myprint(2, module, __FILE__, __LINE__, __func__, format, __VA_ARGS__)
#define print_v(module, format, ...) \
myprint(0, module, __FILE__, __LINE__, __func__, format, __VA_ARGS__)
#define print_v(module, format, ...) \
myprint(0, module, __FILE__, __LINE__, __func__, format, __VA_ARGS__)
#define print_v(module, format, ...) \
myprint(0, module, __FILE__, __LINE__, __func__, format, __VA_ARGS__)
#define ENABLE_USE_TYPE_1 1
#ifdef ENABLE_USE_TYPE_1
#define PLOG_V(module, format, ...) print1_v("TYPE1", format, ##__VA_ARGS__)
#define PLOG_D(module, format, ...) print1_d("TYPE1", format, __VA_ARGS__)
#define PLOG_I(module, format, ...) print1_i("TYPE1", format, __VA_ARGS__)
#else
#define PLOG_V(...) print_v(__VA_ARGS__)
#define PLOG_D(...) print_d(__VA_ARGS__)
#define PLOG_I(...) print_i(__VA_ARGS__)
#endif
int main() {
PLOG_V("123", "test %d, %s", 1234, "hello world !");
return 0;
}
运行结果如下:
注释掉:#define ENABLE_USE_TYPE_1 1
运行结果如下: