Search code examples
c++functionlambdaauto

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?


Solution

  • 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.