简体   繁体   English

相当于python代码的C ++:'function(* list)'

[英]C++ equivalent to python code: 'function(*list)'

In python i can do: 在python中,我可以执行以下操作:

def foo(a,b,c):
    print a+b+c

l=[5,2,10]
foo(*l)

Can i do the same in c++? 我可以在C ++中做同样的事情吗?

I believe the closest equivalent is to use a tuple with the (experimental) apply function: 我相信最接近的等效项是使用具有(实验性)apply函数的元组:

#include <tuple>
#include <iostream>
#include <experimental/tuple>

using std::cout;
using std::make_tuple;
using std::experimental::apply;

int main()
{
  auto foo = [](int a,int b,int c)
  {
    cout << a+b+c << "\n";
  };

  auto l = make_tuple(5,2,10);

  apply(foo,l);
}

The closest you can get to is creating a custom type with member variables for each argument, and overload the function to accept either individual values or the custom type. 最接近的是使用每个参数的成员变量创建一个自定义类型,并使函数重载以接受单个值或自定义类型。 The second overload then calls the first. 然后第二个重载调用第一个。

Example: 例:

#include <iostream>

void foo(int a, int b, int c)
{
    std::cout << a + b + c << "\n";
}

struct foo_args { int a; int b; int c; };

void foo(foo_args const& args)
{
    foo(args.a, args.b, args.c);
}

int main()
{
    foo_args const l { 5, 2, 10 };
    foo(l);
}

As you can see, it's not really worth the trouble, though. 如您所见,这确实不值得麻烦。 Different language, different idioms. 不同的语言,不同的习语。

It's a little different in C++, but I believe you can still do what you want there. 在C ++中,它有些不同,但是我相信您仍然可以在其中做您想做的事情。

#include <iostream>
#include <vector>

void foo(int a, int b, int c) {
    std::cout << a + b + c << std::endl;
}
void foo(const int (&arr)[3]) { //foo overloaded for arrays of size 3
    foo(arr[0], arr[1], arr[2]); //Calls the original foo
}
void foo(const std::vector<int>& v) { //foo overloaded for vectors
    if(v.size() >= 3) //Vector should at least have 3 elements
        foo(v[0], v[1], v[2]); //Calls the original foo
}

int main(void) {

    foo(10, 20, 30);
    int arr[3] {40, 50, 60};
    foo(arr);
    std::vector<int> v {70, 80, 90};
    foo(v);

    getchar();
    return 0;
}

不幸的是,这对于C ++是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM