C++不定参数用法实践

来源:互联网 发布:php正则表达式函数 编辑:程序博客网 时间:2024/05/19 12:40

简介

       介绍可参见链接:http://www.cppblog.com/woka/archive/2009/05/24/85556.aspx     

项目应用

      最近项目中用到sqlite,但是其提供的都是C API的,需要对C API封装成CPP形式,方便使用;

由于sqlite单条sql语句的执行比批量sql语句执行要慢非常非常多。因此我希望能够有这么两个StringBuffer类,分别提供如下功能:

Class StringBuffer:提供快速的字符串拼接功能,例如 buffer+= "insert into .....";

Class SqliteBuffer:提供类似CString.Format的功能,方便进行Sql语句的组合,例如 buffer.Format( "insert into ..... Valuse(%d,%s)", 5, "new");

查看CString.Format的函数声明如下

// Format data using format string 'pszFormat'void __cdecl Format(_In_z_ _FormatMessage_format_string_ PCXSTR pszFormat, ...);

在VS2010中无法查看源代码实现,这个让人非常头疼。而在VS6.0中,查看到的源代码非常的长,粗略估计了下至少有150行代码吧。

虽然sqlite提供了fomat函数,但是这样会让 SqliteBuffer 类依赖了sqlite,于是决定自己写一个。

示例代码

       出于其他考虑,虽然应用于产品代码的SqliteBuffer有更好的封装,但是在这里只示例不定参数的简单代码

#ifdef _UNICODEstatic_assert( false, "_UNICODE not supported now");#endif#include <string>#include <stdio.h>#include <stdarg.h>#include <assert.h>#include <vector>class CStringBuffer{public:CStringBuffer(){}~CStringBuffer(){}const char* GetString() const{return m_strBuffer.c_str();}const char* Format( const char* szFormat, ... ){assert( nullptr != szFormat );va_list ap;va_start( szFormat, ap );int len = _vscprintf( szFormat, ap ) + 1; // for str end '\0'std::vector<char> buffTemp;buffTemp.reserve( len );buffTemp.push_back( 0 );vsprintf( &buffTemp[0], szFormat, ap );va_end( ap );std::string strTemp( &buffTemp[0] );m_strBuffer = strTemp;return m_strBuffer.c_str();}private:std::stringm_strBuffer;};

如何使用

CStringBuffer strBuffer;strBuffer.Format( "insert into table values(%d,%s,%f,%02f)", 2, "str", 3.2222, 3.2222 );
原创粉丝点击