Pages

Thursday, 9 June 2022

Chapter 24 // Exercise 3 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2019 and a modified version of the std_lib_facilities header found here.

Chapter 24 // Exercise 3

Expert level only (this cannot be done with the facilities described in this book): Write an apply(f, a) that can take a void(T&), a T(const T&), and their function object equivalents. Hint: Boost::bind.


I was determined to complete this exercise...I mean he basically challenged me by saying it's "Expert level only".

I bashed my head against the wall for many hours. I knew it had something to do with the return type of the function and checking for void. Eventually I posted in our works discord and template wizard Keith came to my rescue. He first suggested to ignore the bind hint and take a look at std::for_each instead.

This helped however I was still having trouble determining if the incoming function at runtime returned void or not. He then hinted at std::result_of. That is deprecated now but I managed to piece together bits from this post on how to use invoke_result:

I got this working for the T(const T&) but it would not compile for void(T&). He then told me to add constexpr to the if (function return type is void), as that would prevent the compiler from doing a compile time branch.....it WORKED.

Getting this small function to work was one hell of a high.




No comments:

Post a Comment