ProblemsModern C++Negate the functor
NoviceModern C++

Negate the functor

Context

Code often has a ready predicate and needs the opposite check. Writing the negated twin by hand duplicates logic; a small wrapper object that stores the original predicate and flips its answer solves it once for every predicate. std::not_fn is the library version of exactly this.

Task

Implement not_functor(f): it takes a predicate object and returns a new one answering the opposite. not_functor(IsEven{})(3) == true. Build the wrapper class yourself — no lambdas, no std.

Constraints

  • not_functor(pred) returns an object; calling it with the same argument gives the negated answer
  • Works for any predicate object with operator()(int)
  • No lambdas and no std types
  • The original predicate keeps working

Before you code

  • What state must the wrapper store?
  • Why is a class template better than one wrapper per predicate type?
  • What does std call this adapter? (std::not_fn)

Tests

  • #1Negation answers the opposite
  • #2Works for any predicate
  • #3Double negation restores the answer

Hints

Hint 1

The wrapper stores a copy of the predicate; its operator() calls the stored one and applies !.

Hint 2

A helper function template deduces F, so callers never spell the wrapper type.

Editornot-functor.cpp
Results

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