Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

519
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda