c++ Pass an array instead of a variable length argument list

送分小仙女□ 提交于 2019-12-12 11:19:44

问题


So I have a function that takes a variable length argument list, for example:

int avg(int count,...){
    //stuff
}

I can call it with avg(4,2,3,9,4); and it works fine. It needs to maintain this functionality.

Is there a way for me to also call it with an array instead of listing the variables? For example:

avg(4,myArray[5]) such that the function avg doesn't see any difference?


回答1:


No there is no such way. You can however make two functions, one that takes a variable number of arguments, and one that takes an array (or better yet, an std::vector). The first function simply packs the arguments into the array (or vector) and calls the second function.




回答2:


void f() {}

template<typename T, std::size_t N>
void f(T array[N])
{
}

template<typename T, typename... Args>
void f(const T& value, const Args&... args)
{
    process(value);
    f(args...);
}



回答3:


No. Since pointers are essentially unsigned integers it would not be able to tell the difference between a memory address and an unsigned integer. Alternatively (as I am sure you wanted to avoid), you would have to do:

avg( 4, myArray[ 0 ], ..., myArray[ 3 ] );

... where ... is myArray at positions 1 and 2 if you wanted to conform with the same parameters as your previous function. There are other ways to do this, such as using C++ vectors.



来源:https://stackoverflow.com/questions/18230178/c-pass-an-array-instead-of-a-variable-length-argument-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!