Exercise 8. Small Buffer Optimization in std::unique_function.

Exercise 8a. Manual vtable-in-data.

Open this wandbox (backup, backup). The file "unique-function.h" contains a complete implementation of unique_function<R(A...)>.

1. Read through the code. (It's only 128 lines! It should take about 10 minutes.) Here are some questions to guide your study:

2. (Optional) Implement the "type-unerasure" primitive

    const std::type_info& unique_function::type() const
by adding a new entry to ContainerVtable. It should take you 9 lines, or maybe 10 depending on your preferred brace style.
You're done with the first part of this set of exercises! Sit back and relax for a moment. We'll show a couple more slides before the next exercise. (But it's okay to read ahead.)

Exercise 8b. Manual vtable-in-code.

Open this wandbox (b, b, b). The file "unique-function.h" contains a complete implementation of unique_function<R(A...)>. The file "old-unique-function.h" is just a copy of the version from Exercise 8a, so that you have it handy for comparison.

1. Read through the code. How does it differ from the code in Exercise 8a?

2. (Optional) Implement the "type-unerasure" primitive

    const std::type_info& unique_function::type() const
by adding a new entry to ContainerVtableImpl. It should take you about 8 lines. You'll have to add a new enumerator to VtableIndex. You can either return a function pointer using the casting trick above, or you can add a new POD parameter to vtable_in_code.
    static auto vtable_in_code(UF& self, VtableIndex vtable_index, UF *dest, const std::type_info **outp)
        -> typename UF::TrampolineType*

3. (Optional) Implement unique_function::type() by giving unique_function a non-static data member of type const std::type_info *. Was that easier? What are the pros and cons of this approach?

Consider the "don't pay for what you don't use" philosophy of C++. Should people be "using" the type() method? Why or why not?


You're done with this set of exercises! Sit back and relax, or optionally, browse the following resources.