读书人

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

发布时间: 2013-09-18 14:17:40 作者: rapoo

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


c++ va_arg va_start va_end
[解决办法]
va_arg 中你说你的类型是int的 而第二种方式中明显你没有遵循规则 传了个字符串 惩罚就是得不到正确结果,办法就是自己写个类似va_arg 功能的函数或者宏 把各个参数都转化为里面最高的那一个 不过话又说回来, 那你还不如在传参的时候传为一致的数据类型呢
[解决办法]
就你这个例子而言,在add函数中,是把所有的参数按照int型来看待的,所以,在函数内,你已经无法区分外面输入的参数是什么类型,你只知道用int去解释。
你应该在能分辨参数类型的时候做出某种选择,而不是在函数内已经转化为int的时候再做出选择。
换句话说,在调用函数之前,把不合格的参数“剔除”。
[解决办法]
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;
}

读书人网 >C++

热点推荐