封装字符串的Format操作

相信即使再讨厌MFC的朋友也不会把厌恶牵扯到CString类上,
而且CString现在也提升为ATL和MFC的共享类。用CString类,
当然不能忘记它的Format方法,其用于格式化字符串。示例操作如下:
CString  strDemo;
strDemo.Format( _T("数字为:%d, 字符串为:%s"), 1, strOther );

很简单的使用.但我总觉得用的太多代码不美观(或许我有点洁癖吧),我总觉得一行代码
的事用两行代码有点多余,于是我封装了StringFormatEx类.该类的封装风格借鉴了
ATL的字符串转换类的风格(如CA2TEX、CT2WEX等),
代码如下:
/*
* 格式化字符串
*/
template
< int t_nBufferLength = 128 >
class StringFormatEx
{
public:
    StringFormatEx( PCTSTR pszFormat, ) 
throw()
    {
        va_list ptr; 
        va_start(ptr, pszFormat);

        CString strFormat;
        strFormat.FormatV( pszFormat, ptr );

        ASSERT( t_nBufferLength 
> strFormat.GetLength() );

        _stprintf_s( m_szBuffer, strFormat );

        va_end(ptr);
    }

    
operator LPCTSTR() throw()
    {
        
return (m_szBuffer);
    }

private:
    TCHAR m_szBuffer[t_nBufferLength];

private:
    StringFormatEx( 
const StringFormatEx& ) throw();
    StringFormatEx
& operator=const StringFormatEx& ) throw();
};

typedef StringFormatEx
<> StringFormat;

使用示例:

//void Test( LPCTSTR lpsz ){}

Test( StringFormat( _T("数字为:%d, 字符串为:%s"), 1, strOther  ) );

posted @ 2009-03-31 20:19  孤竹君  阅读(340)  评论(2编辑  收藏  举报