添加可变数量的数字 [英] Addition of variable number of numbers
问题描述
我试图写一个函数,它接受不同数据类型的多个参数,并返回数字的和。它应该能够决定用于总和的数据类型。例如,
如果我写add(3,1,2,3)它应该返回sum作为一个int。然而,如果我写add(3,1,2.5,3.25)它应该返回sum作为双。
我试过使用模板,但给出编译时错误。这里是函数
template< typename T>
T add(int n,...)
{
T sum = 0;
va_list vl;
va_start(vl,n);
for(int i = 0; i {
sum + = va_arg(v1,T);
}
va_end(vl);
return sum;
}
int main()
{
std :: cout<<< add(3,1,2,3)
return 0;
}
编译错误:没有匹配的函数调用'add int,int)'。
我认为错误来了,因为我通过了va_arg T,但是我不知道还有什么要传递给它。
为什么不使用 Varidaic模板? - Mohit Jain
如果你可以写在C ++ 14:
template< typename T&
inline T sum(T t){
return t;
}
template< typename T,typename ... Ts>
inline auto sum(T t,Ts ... ts){
return t + sum(ts ...);
}
#include< iostream>
int main(){
std :: cout<< sum(2.5,2)<<'\\\
'
< ;<'\ n'
<<<< sum(1u,2.5,3.f,'0')<如果你在C ++ 11下编写MSVC ++() http://stackoverflow.com/q/25832729/3821804\">在g ++ 下无法使用): template< typename T>
inline T sum(T t){
return t;
}
template< typename T,typename ... Ts>
inline auto sum(T t,Ts ... ts) - > decltype(t + sum(ts ...)){
return t + sum(ts ...)
}
#include< iostream>
int main(){
std :: cout << sum(2.5,2)<'\\\
'// works
& 2.5)<<'\\\
'// works
<< sum(1u,2.5,3.f,'0')< VC ++,但不在g ++下$ b $ b}
I am trying to write a function which accepts multiple arguments of different data types and return the sum of numbers. It should be able to decide what data type to be used for sum. For e.g.
if I write add(3,1,2,3) it should return sum as an int. However, if I write add(3,1,2.5,3.25) it should return sum as a double.
I tried using template, but giving compile time error. Here is the function
template <typename T>
T add(int n, ...)
{
T sum = 0;
va_list vl;
va_start(vl,n);
for(int i=0;i<n;i++)
{
sum += va_arg(vl,T);
}
va_end(vl);
return sum;
}
int main()
{
std::cout<<add(3,1,2,3);
return 0;
}
Compile Error: no matching function for call to 'add(int, int, int, int)'.
I think error is coming because I passed in va_arg T, but i don't know what else to pass to keep it generalised.
解决方案
Why don't you use Varidaic Templates? – Mohit Jain
If you can write in C++14:
template<typename T>
inline T sum(T t){
return t;
}
template<typename T, typename... Ts>
inline auto sum(T t, Ts... ts){
return t+sum(ts...);
}
#include<iostream>
int main(){
std::cout<<sum(2.5, 2)<<'\n'
<<sum(2, 2.5)<<'\n'
<<sum(1u, 2.5, 3.f, '0')<<'\n';
}
If you write in C++11 under MSVC++ (it doesn't work under g++):
template<typename T>
inline T sum(T t){
return t;
}
template<typename T, typename... Ts>
inline auto sum(T t, Ts... ts)->decltype(t+sum(ts...)){
return t+sum(ts...);
}
#include<iostream>
int main(){
std::cout<<sum(2.5, 2)<<'\n' //works
<<sum(2, 2.5)<<'\n' //works
<<sum(1u, 2.5, 3.f, '0')<<'\n';//works under VC++, but not under g++
}
这篇关于添加可变数量的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!