最近写通讯的,刚开始发送不同的格式的数据,写几个重载的,觉得,麻烦
就写成这个样子,虽然不怎么美观,但是用起来还不错。
如果 可以的话,求改进。
使用了boost的函数,偷懒了下
注:日记..字符串拼接
代码
#include "stdafx.h"
#include "iostream"
#include "string"
#include "boost/lexical_cast.hpp"
#include "conio.h"
#include <stdarg.h>
template<class ArguType>
bool StrC( va_list &va_pstr,std::string& allCatString )
{
std::stringstream ss;
ArguType temp;
temp = va_arg( va_pstr, ArguType );
ss<<temp;
ss.clear(NULL);
if ( strcmp(typeid( ArguType ).name() ,"char*" ) || strcmp(typeid( ArguType ).name() ,"const char*" ) )
{
// strcmp(reinterpret_cast<char*>(temp),"\r\n");
if ( boost::lexical_cast<std::string>(temp) == std::string("\r\n") )
{
allCatString.erase( allCatString.end()-1 );
allCatString += ss.str() ;
return false;
}
else
{
allCatString += ss.str() +',';
}
}
else
{
allCatString += ss.str() +',';
}
ss.clear();
return true;
}
template<class T1=char*, class T2=char*, class T3=char*,class T4=char*,class T5=char*,
class T6=char*,class T7=char*,class T8=char*,class T9=char*,class T10=char*>
class TemStrCat
{
public:
static std::string StrCat( const T1 t1=0,... )
{
std::string allCatString = "";
std::stringstream ss;
va_list va_pstr;
va_start(va_pstr, t1 );
int nIndex = 2;
ss.clear();
ss<<t1;
allCatString = ss.str() + ',';
while ( true && nIndex <11 )
{
switch ( nIndex )
{
case 2:{
if ( StrC<T2>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 3:{
if ( StrC<T3>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 4:{
if ( StrC<T4>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 5:
{
if ( StrC<T5>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 6:
{
if ( StrC<T6>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 7:
{
if ( StrC<T7>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 8:
{
if ( StrC<T8>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 9:
{
if ( StrC<T9>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
case 10:
{
if ( StrC<T10>(va_pstr,allCatString) ==false)
{
nIndex=999;
}
nIndex++;
}
break;
}}
std::cout<<allCatString.c_str()<<std::endl;
return allCatString;
}
};
实现:
TemStrCat<char*,double,int,char*,char*>::StrCat("hello",5.26,56,"^_^","\r\n");
TemStrCat<int,int,int,int,char*>::StrCat(123,456,789,258,"\r\n");
TemStrCat<double,double,double,double,char*>::StrCat(123.456,456.789,789.369,258.147,"\r\n");
输出: hello,5.26,56,^_^
123,456,789,258
123.456,456.789,789.369,258.147