ProblemsModern C++Two arguments become one
IntermediateModern C++

Two arguments become one

Context

An API expects single-argument callbacks, but the useful functions take two arguments. Instead of writing an adapter per function, bind the second argument once: the returned object remembers both the function and the value. This is partial application — std::bind does it in general form.

Task

Implement toOneArg(f, x): given a two-argument function and a value for the SECOND argument, return an object callable with one argument. toOneArg(plus, 1) is an increment.

Constraints

  • toOneArg(f, x) returns an object; calling it with a gives f(a, x)
  • The value binds to the SECOND parameter (toOneArg(minus, 1)(2) == 1)
  • The returned object is reusable
  • No std::bind / std::function

Before you code

  • What two things does the returned object capture?
  • Why does binding the second argument (not the first) matter for minus?
  • How does this generalize to N arguments? (std::bind, lambdas)

Tests

  • #1Increment and decrement
  • #2The object is reusable and independent

Hints

Hint 1

The object stores a function pointer and the bound value; operator()(a) forwards both.

Editorto-one-arg.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.