Implementing a Function that Returns a Function

Lesson Introduction

Welcome to this lesson on implementing a function that returns another function in C++. By the end of this lesson, you will understand how to create higher-order functions that can return other functions. This concept is useful in scenarios where you want to create customizable or deferred behavior in your programs, such as factory functions that generate specific functions at runtime.

Concept Overview

Higher-order functions either take other functions as arguments or return them. They help create flexible, reusable code. When returning a function, consider it a "function generator" that can create specific functions based on runtime parameters.

This approach is valuable when you need functions with different behaviors based on parameters. Instead of writing multiple similar functions, you only need one generator function.

We'll use std::function and lambda expressions to create a function that returns another function. This is often called a "factory function." Our example will generate incrementing functions based on a given increment value.

Step-by-Step Implementation: Part 1

The incrementor function:

C++
#include <functional>

std::function<int(int)> incrementor(int increment) {
    return [increment](int x) {
        return x + increment;
    };
}

int main() {return 0;}
  • Signature: It returns std::function<int(int)>, indicating it returns a function that takes and returns an int.
  • Return Statement: It returns a lambda that captures increment by value and takes an integer x, returning x + increment.

This way, this function creates another function, which increments its input value by increment, and returns the result.

Step-by-Step Implementation: Part 2

Let's consider the main function:

C++
#include <iostream>
#include <functional>

std::function<int(int)> incrementor(int increment) {
    return [increment](int x) {
        return x + increment;
    };
}

int main() {
    auto inc3 = incrementor(3);  // Returns a function that adds 3
    std::cout << "Increment 5 by 3: " << inc3(5) << '\n';  // Output: Increment 5 by 3: 8

    return 0;
}
  • Function Call: incrementor(3) returns a function that adds 3. We store it in the inc3 variable.
  • Calling the Returned Function: inc3(5) increments 5 by 3, producing 8.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal