集类型的可变长度参数列表 [英] Variable length argument list of set type

查看:122
本文介绍了集类型的可变长度参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我是pretty肯定,这已经在一些这样或那样讨论过,但我显然太愚蠢找到它。

Alright, I'm pretty sure that this has been discussed before in some way or another, but I'm apparently too stupid to find it.

第一:我不是在寻找va_list的另一个宏。
我所寻找的是类似主函数的参数。

First: I'm NOT looking for va_list and the other macros. What I am looking for is something like the main-function parameters.

默认的原型,因为所有你知道的是:

The default prototype, as all of you know is:

int main(int argc, char *argv[]);

现在,我要为我的程序类似的东西,但不知道究竟怎么了。

Now, I want something similar for my program, but don't know how exactly.

让我们假设有这样的功能:

Let's assume we have this function:

void Function(int argc, unsigned short *args[]) {
    for(int i = 0; i < argc; ++i) printf("%hu ", args[i]);
}

和我想是这样的函数调用:

And I want something like this function call:

Function(5, 1, 2, 3, 4, 5);

将这项工作?
因为我不想在混乱的va_list的,我也不想要创建:

Would that work? Because I don't want the 'cluttering' of va_list, nor do I want to create:

void AnotherFunction() {
    unsigned short Args[] = { 1, 2, 3, 4, 5 };
    Function(5, Args);
}

很简单,因为在这种情况下我只需要一个简单的指针。
可能有人请点我朝着正确的方向?非常感谢你。

Simply because in that case I would only need a simple pointer. Could someone please point me in the right direction? Thank you very much.

编辑:
谢谢大家对您的宝贵意见。我会满足于不标准的C / C ++,现在的工作,并寻找一个不同的方法来我的问题。

Thank you everyone for your valuable input. I'll settle for 'Doesn't work with standard C/C++ for now and look for a different approach to my problem.

再次非常感谢你。

推荐答案

一个g ++的特定解决方案:

A g++ specific solution:

const size_t MAX_ARGS = 42;

void Function(int argc, const unsigned short (&args)[MAX_ARGS])
{
}

int main()
{
    Function(5, {1,2,3,4,5});
}

如果你实际上并不需要的 ARGC 参数,你可以写一个模板:

If you don't actually need the argc parameter, you can write a template:

template<size_t N>
void Function(const unsigned short(&args)[N])
{
    // use N
}

这工作在C ++ 03。数组必须是const,否则你不能传递一个临时的初始化列表这样。如果您需要修改函数内部的元素,你需要进行复印。

This works in C++03. The array needs to be const, or else you can't pass a temporary initializer list like that. If you need to modify the elements inside the function, you'll need to make a copy.

这篇关于集类型的可变长度参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆