如何在标准C ++ 17中将临时数组传递给函数 [英] How to pass a temporary array to a function in standard C++17
问题描述
我具有以下签名的功能:
I have a function of the following signature:
void foo(int argc, char const * const argv[]);
我想用一种简洁的方式来称呼它,类似但不必如下: / p>
I would like to call it in a concise way, similar, but not necessary identical as below:
foo(3, {"one", "two", "three"});
我知道C仅为此目的支持复合文字(参考)。
I know that C supports compound literals just for this purpose (reference).
我也知道如何使用模板(参考)来解决问题。
I also know how to solve the problem using templates (reference).
但是,我的问题略有不同。函数签名是固定的-通常接受传递给 main
的参数,并且数组的大小不是预定义的。我正在为此功能编写测试,就我而言,所传递的数组在编译时是已知的。
However, my problem is slightly different. The function signature is fixed - it normally takes arguments passed to main
and the size of the array is not predefined. I am writing tests for this function and in my case the passed arrays are known at compile-time.
是否可以调用 foo
而不使用下面的临时变量或包装函数?
Is there a way to call foo
without using temporary variables or wrapper functions like below?
char const * array[3] = {"one", "two", "three"};
foo(3, array);
template<int N>
void wrapper(char const * const (&array)[N])
{
foo(N, array);
}
推荐答案
尽管我不知道如何
template<size_t N>
void foo(int argc, const char *(&&argv)[N]){
int i=0;
for( auto o: argv) {
++i;
cout<<"array"<<i<<" = " << o<<"\n";
}
cout<< "\narray size "<<i<<"\n"<<argc<<"\n";
return;
}
int main(){
foo(3, {"one", "two", "three"});
}
array1 = one
array2 = two
array3 = three
array size 3
3
这篇关于如何在标准C ++ 17中将临时数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!