Thursday, 7 January 2021

Chapter 19 // Exercise 2 - Principles & Practice Using C++

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

Chapter 19 // Exercise 2

Write a template function that takes a vector<T> vt  and a vector<U> vu as arguments and returns the sum of all vt[i]*vu[i]s.


This one confused me for a bit as I pondered the best way to compare types. I had previously found a predicate called is_same that checks if to templated types are the same. It's defined in the <type_traits> header. There is a plethora of good stuff in there, along with common_type. This predicate takes in two templated types and if they are similar enough (think ints and floats) then common_type will deal with operations for you.

This also works as a concept. In section 19.3.3 I got very confused as Concepts have only just been introduced in C++20 so the concepts he's referring to here must mean something else now. I think of them as template predicates. Useful but horrible to look at.

No comments:

Post a Comment