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

346
Vistas
What is the best (or standard) way of switching between functions?

The C++ code below is a simplified version of what I want to do, just to display the general structure.

In each case of the "primary_function()" the structure is identical:

function() + 2

The only thing that changes is the function that is used (function 1, 2, 3, or 4).

Is there a more efficient way to do this so that I am not "repeating" code in each case? Thank you.

#include <iostream>

using namespace std;

int function1(int a){
    return a;
}

int function2(int b){
    return b*b;
}

int function3(int c){
    return c*c + c;
}

int function4(int d){
    return 5*d;
}

int primary_function(int x, int selection){

    switch(selection){
        case(1):
            return function1(x) + 2;
            break;
        case(2):
            return function2(x) + 2;
            break;
        case(3):
            return function3(x) + 2;
            break;
        case(4):
            return function4(x) + 2;
            break;
    }
}



int main(){

    cout << primary_function(6,1) << endl;
    cout << primary_function(6,2) << endl;
    cout << primary_function(6,3) << endl;
    cout << primary_function(6,4) << endl;
    
    return 0;
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use an array of function pointers as follows:

int primary_function(int x, int selection) {

    using fn_ptr_t = int (*)(int);
    static fn_ptr_t functions[] = {
        function1,
        function2,
        function3,
        function4
    };

    return functions[selection - 1](x) + 2;
}

You can also use std::function<int(int)> as the item type of the array which would allow you to use lambdas, even with closures, in the array instead of only named functions.

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