Yuan Yijun (bbbush) wrote,
Yuan Yijun
bbbush

写 Log

老师讲 c++ 的时候不认真听,花了一个星期时间重学 templates 那一段,写出来的代码稀里糊涂的。

需求:一个 Log 接口,可以生成 容易解析的 输出,然后不用有太多功能了。结果我搞了个有六个参数的模板,叫做
"Logger",有三个参数是必需的:输入类型 LogItem,输出类型 CString,一个 Level 类型。可是这个 Level
类型不加也可以,函数参数加个 level 枚举就可以了,加上了的结果就是下面的乱七八糟:感觉是完全失掉了模板的本意 :(


	template<ILogPolicy::Level level>
	class Level_traits
	{
	public:
		enum{value = level};
		typedef Level_traits<level> type;
		static LPCTSTR name;
	};

	typedef Level_traits<ILogPolicy::LEVEL_ALL> LEVEL_ALL;
	LPCTSTR LEVEL_ALL::name = _T("NOTIFICATION");

	typedef Level_traits<ILogPolicy::LEVEL_VERBOSE> LEVEL_VERBOSE;
	LPCTSTR LEVEL_VERBOSE::name = _T("DEBUG");

	typedef Level_traits<ILogPolicy::LEVEL_INFO> LEVEL_INFO;
	LPCTSTR LEVEL_INFO::name = _T("INFO");

	typedef Level_traits<ILogPolicy::LEVEL_WARNING> LEVEL_WARNING;
	LPCTSTR LEVEL_WARNING::name = _T("WARNING");

	typedef Level_traits<ILogPolicy::LEVEL_FATAL> LEVEL_FATAL;
	LPCTSTR LEVEL_FATAL::name = _T("FATAL");


	template<class LogItem>
	void LogT(const LogItem& item)
	{
		switch(item.eLevel)
		{
		case ILogPolicy::LEVEL_FATAL:
			typedef LEVEL_FATAL LEVEL;
			Logger<LogItem, CString, LEVEL_FATAL>::WriteLog(item);
			break;
		case ILogPolicy::LEVEL_WARNING:
			Logger<LogItem, CString, LEVEL_WARNING>::WriteLog(item);
			break;
		case ILogPolicy::LEVEL_INFO:
			Logger<LogItem, CString, LEVEL_INFO>::WriteLog(item);
			break;
		case ILogPolicy::LEVEL_VERBOSE:
			Logger<LogItem, CString, LEVEL_VERBOSE>::WriteLog(item);
			break;
		case ILogPolicy::LEVEL_ALL:
			Logger<LogItem, CString, LEVEL_ALL>::WriteLog(item);
			break;
		}
	}


Tags: 工作
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments