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

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

问题描述

好吧,我很确定之前已经以某种方式讨论过这个问题,但我显然太笨了,找不到它.

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.

假设我们有这个函数:

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.数组必须是常量,否则你不能像这样传递临时初始化列表.如果您需要修改函数内部的元素,则需要进行复制.

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天全站免登陆