Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass tuple elements to callable in C++

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading