Home > Enterprise >  How to pass tuple elements to callable in C
How to pass tuple elements to callable in C

Time:10-02

How do I pass the elements of a tuple as arguments to any callable in C ? std::apply works only when the callable's arguments exactly match those of the tuple's.

For instance:

struct Foo {
   template<typename... Ts>
   Foo(std::string s, Ts&&... ts) {}
}

int main() {
   auto tup = std::make_tuple(5, 5.5f, 100000l);
}

In the code above, how would I make a Foo object by passing into its constructor some string value followed by the values stored in tup?

CodePudding user response:

Either you can specify template arguments, thereby choosing the overload; or, you might do a simple forwarding lambda:

Foo f = std::apply([&](auto&&... args){ return Foo("", std::forward<decltype(args)>(args)...);}, tup);

Note that here I have added the first parameter as a string; an int is not accepted by Foo there.

  • Related