Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning 2 lambdas from a tuple using tie

I have a function which returns a std::tuple of lambdas and i want to assign each lambda to a variable using std::tie()

#include<tuple>
#include <iostream>
using namespace std;

auto fn(){
    auto f1 = []() {cout << "ran 1" << endl;};
    auto f2 = []() {cout << "ran 2" << endl;};
    return make_tuple(f1, f2);
}

int main()
{
    auto res = fn();
    auto f1,f2; // doesn't compile
    tie(f1, f2) = res;

    f1();
    f2();
    return 0;
}

The problem is that lambdas have to be from type 'auto' since they are resolved at compile time, but i cannot declare variables as auto without defining them. So what can i do to get this code to compile?

like image 432
Bl4ckC4t Avatar asked Dec 06 '25 03:12

Bl4ckC4t


1 Answers

C++17 introduced structured bindings that will do this for you. Using

const auto& [f1, f2] = fn();

will create a reference to the returned object extending it's lifetime and introduce f1 and f2 as names to the members of the tuple.

like image 139
NathanOliver Avatar answered Dec 07 '25 19:12

NathanOliver



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!