Search code examples
c++lambdascopechained

How to implement sequential processing using lambdas or function objects?


The following is a MWE explaining the logical scenario:

#include<iostream>

class sample{
    sample()=default;
    ~sample=default;
    sample(const sample&)=delete;
    sample operator=(const sample&)=delete;
    int calculate (int);
    
};

int sample::calculate(int n){
    
    auto lambda1 = [&](int n)->void{
        
        //do some processing
        
        lambda2();
    };
    
    auto lambda2 = [&]()->void{
        
        //do some processing
        lambda3();
        
    };
    
    auot lambda3 = [&]()->void{
        
        //do some processing
        
    };       
 //return result
}

int main(){
    sample s;
    int n = <some integer value>;
    auto result = s.calculate(n);
    std::cout << result << std::endl;

 return 0;  
} 

As can be seen, the idea is to sequentially invoke lambdas defined within a class method. The implementation approach as shown won't compile as lambda1 doesn't know about lambda2 and lambda2 doesn't know about lambda3.

I tried replacing the lambdas with function objects but the error persists.

Would it be possible to forward declare the logic encapsulated within each of the lambda by means of function objects (or by any other means), so that the above logic can be implemented successfully?

TIA

Vinod


Solution

  • Without discussing the approach itself, as a trivial solution, you might simply reorder lambdas, so that each lambda is defined before it is captured:

    // more lambdas
    
    auto lambda2 = [&] {
        // do something
    };
    
    auto lambda1 = [&](int n) {
        // do something
        lambda2();
    };