Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass vector elements to a function in c++

Tags:

c++

I now have a vector of objects. And a pre-defined function that can take objects as parameters. Just curious if there's a way of passing these objects to this function?

std::vector<obj> objects; //contains obj1, obj2 .., objn

And I'd like to achieve something like this:

 foo(obj1, obj2 ... , objn) //foo can take as many objects as I want
like image 975
Grey258 Avatar asked Sep 20 '26 16:09

Grey258


1 Answers

While common in scripted languages like P(ython|erl), this still requires a library solution in C++. Something like

template<typename F, class Container> inline decltype(auto) apply(F f, Container const &args) {
    switch(args.size()) {
        case 0: return f();
        case 1: return f(args.front());
        case 2: return f(args[0], args[1]);
        case 3: return f(args[0], args[1], args[2]);
        // and so forth
        default: throw std::range_error("f does not accept that many arguments!");
    }
}
like image 153
bipll Avatar answered Sep 23 '26 05:09

bipll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!