Uses of pointers non-type template parameters?

后端 未结 5 1027
小蘑菇
小蘑菇 2020-12-13 11:03

Has anyone ever used pointers/references/pointer-to-member (non-type) template parameters?
I\'m not aware of any (sane/real-world) scenario in which that C++ feature sho

5条回答
  •  误落风尘
    2020-12-13 11:21

    Occasionally you need to supply a callback function having a particular signature as a function pointer (e.g. void (*)(int)), but the function you want to supply takes different (though compatible) parameters (e.g. double my_callback(double x)), so you can't pass its address directly. In addition, you might want to do some work before and after calling the function.

    It's easy enough to write a class template that tucks away the function pointer and then calls it from inside its operator()() or some other member function, but this doesn't provide a way to extract a regular function pointer, since the entity being called still requires the this pointer to find the callback function.

    You can solve this problem in an elegant and typesafe way by building an adaptor that, given an input function, produces a customised static member function (which, like a regular function and unlike a non-static member function, can have its address taken and used for a function pointer). A function-pointer template parameter is needed to embed knowledge of the callback function into the static member function. The technique is demonstrated here.

提交回复
热议问题