ProblemsModern C++Functors behind one pointer
AdvancedModern C++

Functors behind one pointer

Context

An initializer_list holds elements of one type — so two different functors can only share a list through a common base pointer. That is type erasure in its rawest form: a virtual operator() behind a base class. std::function does the same job with more comfort; here you build the skeleton.

Task

Make a range-for over {make_increment<int>(), make_twice<int>()} work: both factories return pointers to a COMMON base with a virtual operator(), so different operations live in one initializer_list and are applied through one call.

Constraints

  • A base class with a virtual operator()(T) and a virtual destructor
  • make_increment<T>() and make_twice<T>() return base pointers to operations +1 and *2
  • The sample loop (range-for over an initializer_list of pointers) compiles and works
  • The caller deletes the pointers — no leaks under ASan

Before you code

  • Why do the two factories have to return the SAME pointer type?
  • What breaks without the virtual destructor?
  • Which std type erases callables like this for real code? (std::function)

Tests

  • #1The polymorphic loop
  • #2Polymorphic call through the base
  • #3Works for another type

Hints

Hint 1

The initializer_list deduces ONE element type — make both factories return Op<T>*.

Hint 2

operator() can be virtual like any other member — override it in each derived operation.

Editorpolymorphic-functors.cpp
Results

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