Wednesday, 15 June 2022

Chapter 24 // Exercise 9 - 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 9

Rewrite the non-member apply() functions to return a Matrix of the return type of the function applied; that is, apply(f, a) should return a Matrix<R> where R is the return type of f. Warning: The solution requires information about templates not available in this book.


Fortunately, as I attempted exercise 3, I already had a way to determine the return type of f by checking to see if it was void:
// if the return type of pFunction is not void
if constexpr (!std::is_same_v<std::invoke_result_t<F, decltype(pContainer[0])>, void>)
This uses std::invoke_result which is C++17, but the C++11 alternative is std::result_of. std::is_same is also available in C++11 so I have a feeling, the std metaprogramming library is what he was hinting at:
https://en.cppreference.com/w/cpp/meta

I used the result of invoke_result to determine the return type then create a matrix of that return type and used auto to let the function determine what it should return.

It works for one specific scenario. I still need more practice with metaprogramming to try and fix this as I was scratching my head as to why it just wouldn't deduce the type. This is definitely an exercise to come back to in the future.

No comments:

Post a Comment