关于c++的不定参数类型和参数个数的函数

jack_leiwin 2013-09-08 12:25:56

int add(int a1,...)
{
va_list arg_ptr;

int sum=0;
int tempValue;

sum=sum+a1;

va_start(arg_ptr,a1)

do
{
tempValue=va_arg(arg_ptr,int);
sum+=tempValue;
}while(tempValue!=0);

va_end(arg_ptr);
return sum;
}


以下两种调用
int main()
{
cout<<add(1,2,3,4,0)<<endl;//输出结果是10
cout<<add(1,2,"book",3,4,0)<<endl;//输出结果就不是10
}


查了一下说那个va_arg不能自动识别参数个数和类型,那么怎么自定一个东西,在va_arg 遍历的时候可以识别所遍历的参数的类型啊?请各位大神给予指导!
也就是后说,遇到上面第二种调用的时候,如果遍历到book的时候直接忽略掉?
...全文
1173 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
lm_whales 2013-09-09
  • 打赏
  • 举报
回复
引用 11 楼 akirya 的回复:
VS2013 G++ 4.4.1 以上版本都可以通过 均输出10
#include <iostream>
using namespace std;

int add( int v );
template<class T>
int add( T v );
template<class T , class ... Types>
int add( T v ,  Types ... args );
template<class ...Types>
int add( int v , Types ... args );


template<class T>
int add( T v )
{
	return 0;
}
int add( int v )
{
	return v;
}

template<class T , class ... Types>
int add( T v ,  Types ... args )
{
	return add( args ... );
}

template<class ...Types>
int add( int v , Types ... args )
{
	return v + add( args ... );
}


int main()
{
	cout<<add(1,2,3,4)<<endl;
	cout<<add(1,2,"book",3,4)<<endl;
}
这个好,但是标准太新 ,只有少数编译器支持,不知道XP上有没有编译器可以运行。
modyaj 2013-09-09
  • 打赏
  • 举报
回复
引用 6 楼 qq120848369 的回复:
楼主是有多不开窍, 我说个printf你就理解成打印。
Adol1111 2013-09-09
  • 打赏
  • 举报
回复
引用 9 楼 jack_leiwin 的回复:
大神啊,能不能多点解释啊?不要总是一句话!
printf不就是不定参数最典型的实例么...谁让你和printf配合使用了...
  • 打赏
  • 举报
回复
VS2013 G++ 4.4.1 以上版本都可以通过 均输出10
#include <iostream>
using namespace std;

int add( int v );
template<class T>
int add( T v );
template<class T , class ... Types>
int add( T v ,  Types ... args );
template<class ...Types>
int add( int v , Types ... args );


template<class T>
int add( T v )
{
	return 0;
}
int add( int v )
{
	return v;
}

template<class T , class ... Types>
int add( T v ,  Types ... args )
{
	return add( args ... );
}

template<class ...Types>
int add( int v , Types ... args )
{
	return v + add( args ... );
}


int main()
{
	cout<<add(1,2,3,4)<<endl;
	cout<<add(1,2,"book",3,4)<<endl;
}
FengPrince 2013-09-09
  • 打赏
  • 举报
回复
变长参数是要你自己控制传递进来的实参的,就是说你展开va_arg宏的时候,你必须要指明参数的类型,编译器编译的时候根本不知道你要传多少个参数,参数类型是什么,这根本无法确定,谁都不可能知道,除了你自己! 所以,你必须要根据你传实参的格式来编写add函数。 比如,你想略过字符串,你就必须在add函数自己写跳过字符串参数的代码。 我给你个参考的例子: fmt里存放的是字符串参数在参数列表中的位置,从0开始,为了省空间我没有使用int数组。 比如 add("3",1,2,"book",3,4,0),因为"book"实参在参数列表的位置为3; add("35",1,2,"book",3,"store",4,0),因为"book"实参在参数列表的位置为3,"store"实参在参数列表的位置为5;

int add(const char* fmt,...)
{
    va_list va;
    int sum=0;
    int temp=1;
    int counts=0;
    va_start(va,fmt);
    do
    {
        if(++counts==*fmt-48)
        {
            ++fmt;
            va_arg(va,char*);
            continue;
        }
        temp=va_arg(va,int);
        sum+=temp;
    }while(temp);
    va_end(va);
    return sum;
}
lm_whales 2013-09-09
  • 打赏
  • 举报
回复
引用 16 楼 rocktyt2 的回复:
[quote=引用 14 楼 lm_whales 的回复:] [quote=引用 11 楼 akirya 的回复:] VS2013 G++ 4.4.1 以上版本都可以通过 均输出10
#include <iostream>
using namespace std;

int add( int v );
template<class T>
int add( T v );
template<class T , class ... Types>
int add( T v ,  Types ... args );
template<class ...Types>
int add( int v , Types ... args );


template<class T>
int add( T v )
{
	return 0;
}
int add( int v )
{
	return v;
}

template<class T , class ... Types>
int add( T v ,  Types ... args )
{
	return add( args ... );
}

template<class ...Types>
int add( int v , Types ... args )
{
	return v + add( args ... );
}


int main()
{
	cout<<add(1,2,3,4)<<endl;
	cout<<add(1,2,"book",3,4)<<endl;
}
这个好,但是标准太新 ,只有少数编译器支持,不知道XP上有没有编译器可以运行。 [/quote]mingw 简单点,装个带编译器的Code::Blocks[/quote] 谢谢!!
赵4老师 2013-09-09
  • 打赏
  • 举报
回复
仅供参考
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
    #include <windows.h>
    #include <io.h>
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  _vsnprintf         vsnprintf
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef WIN32
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    _vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;

    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
int main(int argc,char * argv[]) {
    int i;
#ifdef WIN32
    InitializeCriticalSection(&cs_log);
#else
    pthread_mutex_init(&cs_log,NULL);
#endif
    for (i=0;i<10000;i++) {
        Log("This is a Log %04d from FILE:%s LINE:%d\n",i, __FILE__, __LINE__);
    }
#ifdef WIN32
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}
//1-78行添加到你带main的.c或.cpp的那个文件的最前面
//81-85行添加到你的main函数开头
//89-93行添加到你的main函数结束前
//在要写LOG的地方仿照第87行的写法写LOG到文件MyLog1.log中
rocktyt 2013-09-09
  • 打赏
  • 举报
回复
引用 14 楼 lm_whales 的回复:
[quote=引用 11 楼 akirya 的回复:] VS2013 G++ 4.4.1 以上版本都可以通过 均输出10
#include <iostream>
using namespace std;

int add( int v );
template<class T>
int add( T v );
template<class T , class ... Types>
int add( T v ,  Types ... args );
template<class ...Types>
int add( int v , Types ... args );


template<class T>
int add( T v )
{
	return 0;
}
int add( int v )
{
	return v;
}

template<class T , class ... Types>
int add( T v ,  Types ... args )
{
	return add( args ... );
}

template<class ...Types>
int add( int v , Types ... args )
{
	return v + add( args ... );
}


int main()
{
	cout<<add(1,2,3,4)<<endl;
	cout<<add(1,2,"book",3,4)<<endl;
}
这个好,但是标准太新 ,只有少数编译器支持,不知道XP上有没有编译器可以运行。 [/quote]mingw 简单点,装个带编译器的Code::Blocks
azhou88 2013-09-09
  • 打赏
  • 举报
回复
哥们,试试用Template ,应该没有问题。
qq120848369 2013-09-08
  • 打赏
  • 举报
回复
看看printf的函数声明, 人家让你传入format的。
jack_leiwin 2013-09-08
  • 打赏
  • 举报
回复
引用 6 楼 qq120848369 的回复:
楼主是有多不开窍, 我说个printf你就理解成打印。
大神啊,能不能多点解释啊?不要总是一句话!
lm_whales 2013-09-08
  • 打赏
  • 举报
回复
各个数据按照,数据的参数长度(不是参数的数据类型的长度),确定 至于找到参数,和类型匹配,靠的只是数据长度,每一种数据类型,根据函数调用的参数传递方式,得到数据长度 在堆栈中直接查找.找到后下一个数据跳过该参数的长度。 比如 char: sizeof(int),short: sizeof(int) long sizeof(long) float :sizeof(double),double sizeof(double) 等等
  • 打赏
  • 举报
回复
编译器新一些的话,可以使用变长模板. 就能够区分开来
qq120848369 2013-09-08
  • 打赏
  • 举报
回复
楼主是有多不开窍, 我说个printf你就理解成打印。
大尾巴猫 2013-09-08
  • 打赏
  • 举报
回复
就你这个例子而言,在add函数中,是把所有的参数按照int型来看待的,所以,在函数内,你已经无法区分外面输入的参数是什么类型,你只知道用int去解释。 你应该在能分辨参数类型的时候做出某种选择,而不是在函数内已经转化为int的时候再做出选择。 换句话说,在调用函数之前,把不合格的参数“剔除”。
modyaj 2013-09-08
  • 打赏
  • 举报
回复
va_arg 中你说你的类型是int的 而第二种方式中明显你没有遵循规则 传了个字符串 惩罚就是得不到正确结果,办法就是自己写个类似va_arg 功能的函数或者宏 把各个参数都转化为里面最高的那一个 不过话又说回来, 那你还不如在传参的时候传为一致的数据类型呢
jack_leiwin 2013-09-08
  • 打赏
  • 举报
回复
引用 1 楼 qq120848369 的回复:
看看printf的函数声明, 人家让你传入format的。
有时候不是为了简单的输出啊,需要根据所得参数的类型来进行相应的操作啊?难道只能与printf等配合使用吗?
jack_leiwin 2013-09-08
  • 打赏
  • 举报
回复
引用 1 楼 qq120848369 的回复:
看看printf的函数声明, 人家让你传入format的。
能说的详细点儿吗?

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧