C++ allows non-type template parameters to be of integral or enumeration type (with integral including boolean and character), as well as pointers and references to arbitrary types.
I have seen integer, boolean, and enumeration parameters used widely and I appreciate their utility. I've even seen a clever use of character parameters for compile-time parsing of strings.
But I'm wondering what are some use cases for non-type template parameters that are pointers or references to arbitrary types?
Using a pointer-to-member-function as a template parameter makes it possible for the compiler to inline a call to that function. An example of this usage can be seen in my answer to this question: How to allow templated functor work on both member and non-member functions
In this example, the pointer-to-member-function in the template parameter enables the generation of a 'thunk' function that contains a call (inlined) to the pointer-to-member-function. A pointer to the thunk function has a generic signature (and fixed size) which enables it to be stored and copied with minimal runtime cost, unlike a pointer-to-member-function.
if you know the address of a buffer at compile time, you can make a decision (at compile time) based on its alignment, especially for things such as memcpy, this allows you to skip any run-time checking, and just jump straight to copying the data using the most efficiently sized types.
(I'm guessing) You might also be able to compile-assert that a pointer passed in is page aligned (useful for e.g. nvme protocol), though I don't know offhand what that would look like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With