C/C++11可变参数打印日志

xingyun86 2020-8-11 986

C++11可变参数打印日志

// TimerCount.h : Include file for standard system include files,
// or project specific include files.
#pragma once
#include <chrono>
#define TIMERSTARTS(tag)  auto tag##_sta = std::chrono::steady_clock::now()
#define TIMEREND_SS(tag)  auto tag##_end = std::chrono::steady_clock::now();std::cout << #tag << " costs " << std::chrono::duration_cast<std::chrono::seconds>(tag##_end - tag##_sta).count() << "s" << std::endl
#define TIMEREND_MS(tag)  auto tag##_end = std::chrono::steady_clock::now();std::cout << #tag << " costs " << std::chrono::duration_cast<std::chrono::milliseconds>(tag##_end - tag##_sta).count() << "ms" << std::endl
#define TIMEREND_US(tag)  auto tag##_end = std::chrono::steady_clock::now();std::cout << #tag << " costs " << std::chrono::duration_cast<std::chrono::microseconds>(tag##_end - tag##_sta).count() << "us" << std::endl
//终止递归函数, 使用可变参数模板实现参数打印到输出流(ostream) (递归调用),剩余参数递归调用
#include <iostream>
__inline static void print_trace_again(std::ostream& os) {}
template<typename T, typename ...Args>__inline static void print_trace_again(std::ostream& os, T arg, Args...args) { os << arg; print_trace_again(os, args...); }
template<typename ... T>void print_trace_debug(T ... args) {print_trace_again(std::cout, args...);}
#define PRINT_DEBUG(...) print_trace_debug("[",__func__,":", __LINE__,"] ", ##__VA_ARGS__)

#if defined(_DEBUG) || defined(DEBUG)
#define MY_PRINT_DEBUG PRINT_DEBUG
#else
#define MY_PRINT_DEBUG
#endif // _DEBUG

如果打印uint8_t为整数(默认会打印为字符),需要如下:uint8_t a = 0x00; MY_PRINT_DEBUG("a=",(unsigned)(a));

C++11可变参数打印类对象信息

#include <iostream>
// 终止递归函数
__inline static std::ostream& output_stream(std::ostream& os) { return os; }
// 使用可变参数模板实现参数打印到输出流(ostream) (递归调用)
template<typename T, typename ...Args>
__inline static std::ostream& output_stream(std::ostream& os, T t, Args...args) { os << t; output_stream(os, args...);  return os; }
template<typename T, typename ...Args>
__inline static std::ostream& LogOut(T t, Args...args) { return output_stream(std::cout, t, args...); }
template<typename T, typename ...Args>
__inline static std::ostream& LogErr(T t, Args...args) { return output_stream(std::cerr, t, args...); }
// 重载 << 操作符,支持std::ostream输出
class CTest {
public:
	/// 友元声明定义
	friend std::ostream& operator << (std::ostream& os, const CTest& test) {
		os << test.a << "+" << test.b << "=" << (test.a + test.b);
		return os;
	}
public:
	CTest(int _a = 1, int _b = 2) :a(_a), b(_b) {}
	~CTest() {}
private:
	int a = 10;
	int b = 2;
};
int main(int argc, char** argv)
{
	LogOut("打印测试\n", (int)2, CTest()) << std::endl;
	return 0;
}

C可变参数打印日志

#define PRINT_DEBUG(fmt,...) printf("[%s]:%d " fmt, __func__, __LINE__, ##__VA_ARGS__)
×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回