Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use case for non-type template parameter that's not of integral/enumeration type?

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?

like image 288
HighCommander4 Avatar asked Mar 03 '13 21:03

HighCommander4


2 Answers

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.

like image 147
willj Avatar answered Nov 05 '22 17:11

willj


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.

like image 31
EHuhtala Avatar answered Nov 05 '22 17:11

EHuhtala