gpt4 book ai didi

programming-languages - 是否有任何编程语言的函数的变量参数不在末尾?

转载 作者:行者123 更新时间:2023-12-03 07:49:48 24 4
gpt4 key购买 nike

Python、C++、Scheme 和其他语言都允许您定义在参数列表末尾采用可变数量参数的函数...

def function(a, b, *args):
#etc...

...可以按如下方式调用:

function(1, 2)
function(1, 2, 5, 6, 7, 8)

等等...是否有任何语言允许您在其他地方使用参数列表执行可变参数函数?像这样的事情:

def function(int a, string... args, int theend) {...}

所有这些都有效:

function(1, 2)
function(1, "a", 3)
function(1, "b", "c", 4)

另外,参数列表中任意位置的可选参数怎么样?

def function(int a, int? b, int c, int... d) {}

function(1, 2) //a=1, c=2, b=undefined/null/something, d=[]
function(1,2,3) //a=1, b=2, c=3,d=[]
function(1,2,3,4,5) //a=1, b=2, c=3, d=[4,5]

最佳答案

下一个 C++ 可以使用以下语法来做到这一点:

void f(int a, std::initializer_list<int> b, int c) {
// b.begin(), b.end(), b.size() allow to access them
}

void g() {
f(1, { 2, 3, 4, 5 }, 2);
}

关于programming-languages - 是否有任何编程语言的函数的变量参数不在末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/388295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com