How to create a first-class function in C++

1 Answer

0 votes
#include <iostream>
#include <functional>   // std::function

// What a first‑class function does:
// It can be stored in a variable
// It can be passed to another function
// It can be returned from a function
// It can capture variables (if it’s a lambda)
// It allows dynamic behavior

// A first‑class function in C++ is created by treating a function as a value
// something you can store in a variable, pass to another function, or return from a function.
// In modern C++, the cleanest way to do this is with std::function, function pointers, or lambdas.

// A normal function
int add(int a, int b) {
    return a + b;
}

// A function that *accepts* a first-class function
// std::function<int(int,int)> means: a callable taking (int,int) → int
void applyOperation(const std::function<int(int,int)>& op) {
    std::cout << "Result: " << op(10, 5) << std::endl;
}

// A function that *returns* a first-class function
std::function<int(int,int)> getMultiplier(int factor) {
    // Return a lambda that captures 'factor'
    return [factor](int a, int b) {
        return factor * (a + b);
    };
}

int main() {
    // 1. Store a normal function as a first-class function
    std::function<int(int,int)> f1 = add;
    std::cout << "add(3,4) = " << f1(3,4) << std::endl;

    // 2. Store a lambda as a first-class function
    std::function<int(int,int)> f2 = [](int a, int b) {
        return a * b;
    };
    std::cout << "lambda multiply = " << f2(3,4) << std::endl;

    // 3. Pass a first-class function to another function
    applyOperation(add);      // passing normal function
    applyOperation(f2);       // passing lambda

    // 4. Return a first-class function from a function
    auto tripleAdder = getMultiplier(3);
    std::cout << "tripleAdder(2,3) = " << tripleAdder(2,3) << std::endl;
}


/*
run:

add(3,4) = 7
lambda multiply = 12
Result: 15
Result: 50
tripleAdder(2,3) = 15

*/

 



answered 10 hours ago by avibootz

Related questions

1 answer 146 views
1 answer 121 views
1 answer 182 views
1 answer 229 views
1 answer 234 views
...