Janus
Janus

Reputation: 175

How to assign function in if condition?

How do I assign a function in a if-condition in C++?

Say I have the functions f1 and f2 (available and defined in the global environment), and some integer i.

I want to define a new function f3, which equals f1 if i = 1 and f2 otherwise.

How to do this?

Pseudo-code of what I want:

if (i == 1)
{
    f3 = f1;
}
else 
{
    f3 = f2;
}

return f3(5);

Upvotes: 4

Views: 319

Answers (3)

pastoruri
pastoruri

Reputation: 31

I think the best option for a polymorphic function is to use a pointer to a function. You can use a pointer like a function, but you can change what it does whenever you need to. Follow this example

void f1(int x1) {
    cout << "f1 "<< x1 << endl;
}

void f2(int x2) {
    cout << "f2 "<< x2 << endl;
}

int main() {

    void (*function_pointer)(int); 

    //Declaration of a function pointer and the type of argument of the function that you 
    // want to point at.

    int x;

    cin >> x;

    if(x == 1) {

        function_pointer = &f1;
    }

    if(x == 2) {

        function_pointer = &f2;
    }

    function_pointer( 2 ); //Usage of a function pointer, as you see, is very similar to a regular 
              // function.

    return 0;
}

Greetings.

Upvotes: 3

Thomas Sablik
Thomas Sablik

Reputation: 16448

You can declare f3 as function pointer. You can use an alias or auto to make it simpler

using F = void(*)(int);
void f1(int) {}

void f2(int) {}

int main() {
    void(*f3)(int);
    F f4 = f1;
    auto f5 = f2;
    int i = 1;
    if (i == 1) {
        f3 = f1;
        f5 = f1;
    } else {
        f3 = f2;
        f4 = f2;
    }
    f3(5);
    f4(10);
    f5(15);
}

The name of a function can be used as a pointer: f1 == &f1

Upvotes: 7

Omarito
Omarito

Reputation: 577

Use std::function defined in the functional header of STL

Example:

#include <functional>
#include <stdio.h>

int foo(int x){
    return x;
}

int bar(int x){
   return x * 2;
}

int main(){
    std::function<int(int)> my_func;
    int condition = 1;
    if (condition == 1){
        my_func = foo;
    }else{
        my_func = bar;
    }
    printf("%d", my_func(5)); // call my_func and print it
}

Upvotes: 5

Related Questions