Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

522
Views
How to return an std::optional lambda?

How can I declare a function that returns an std::optional lambda? e.g.

<what_do_i_put_here?> foo(bool b) {
    if(b) return std::nullopt;
    return [](int) { ... };
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

How about using the ternary operator? It will automatically deduce the correct optional type

#include <optional>
auto foo(bool b) {
  return b ? std::nullopt : std::optional{[](int){}};
}
over 4 years ago · Santiago Trujillo Report

0

You can add a level of indirection to deduce the type via auto and decltype:

#include <optional>

auto foo_impl(){
    return [](int){};
}

std::optional<decltype(foo_impl())> foo(bool b) {
    if(b) return std::nullopt;
    return foo_impl();
}
over 4 years ago · Santiago Trujillo Report

0

You can do it something like the following

#include <iostream>
#include <optional>

auto f( bool b )
{
    auto l = [] { std::cout << "Hello World!";  };
    std::optional<decltype( l )> opt;

    if (b)
    {
        // some code
        opt = l;
    }
    else
    {
        // some other cod
    }

    return opt;
}

int main()
{
    ( *f( true  ) )( );
}

Another way is to use std::function with std::optional as for example

std::optional<std::function<void( int )>> g( bool b )
{
    if (b)
    {
        return std::function<void( int )>( []( int x ) { std::cout << x;  } );
    }
    else
    {
        return std::function<void( int )>( []( int x ) { std::cout << 2 * x; } );
    }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!