Consider that you want to call 100 functions sequentially.
I want to create a map that holds function pointers and function parameters, so that i can iterate the map and call each function with the associated parameters.
The arguments are of different type, arity and return type. Is it possible to implement such map in C++?
Pseudocode
for function in map
// call the function with the arguments from the map
function(map[function])
As stated in the comments, this question is too broad. Therefore, there are too many possible solutions. Also, I really wonder why you need this kind of map of functions. I'm sure if you explained your problem, many would advise you a different kind of solution.
That said, I find the subject interesting, and tried to implement a possible solution to your problem.
As the subject is very broad and the question not specific enough, I had to make some decisions (also based on the comments):
I used a set instead of a map as I had no idea what the (key,value) of the map should be.
I just print out the results (assuming the result is printable), as I have no idea what to do with the result.
Instead of function pointers, I used function objects.
As I was not able to fully understand the pseudo code, the functions are called by an invoke function.
Modifying the below example code should allow you to get what you exactly want. The below code is just an example of what kind of ingredients you might need.
GenericFunction and the set
You can only save one type in a set (or map), so you need some GenericFunction class:
class GenericFunction
{
public:
virtual ~GenericFunction() = default;
virtual void invoke() const = 0; // the method to invoke the function
};
Now, you can define a set which will contain pointers to GenericFunction objects:
std::set<GenericFunction*> myFcts;
Specific function class
Next, let's implement the specific function class which derives from the GenericFunction class. The goal of this class is to store the function and arguments of your choice, and to provide an implementation of the invoke function.
#include <iostream>
#include <tuple>
template <typename Fct, typename ... Args>
class MyFct : public GenericFunction
{
public:
MyFct(Fct fct, Args&& ... args) :
_fct { std::move(fct) },
_args { std::forward<Args>(args)... }
{}
void invoke() const override { std::cout << std::apply(_fct,_args) << std::endl; }
private:
Fct _fct;
std::tuple<Args ...> _args;
};
Testing: sum function
For testing, let's write a simple sum function:
template <typename T>
auto sum(T a)
{
return a;
}
template <typename F, typename ... R>
auto sum(F first, R ... rest)
{
return first + sum(rest...);
}
main function
We can now use the above code like this:
#include <set>
int main()
{
// function wrapper
auto sum_wrapper = [](auto&&... args)
{
return sum(std::forward<decltype(args)>(args)...);
};
// create a specific function
MyFct myf1(sum_wrapper, 1, 2.33/*, add the args of your choice*/);
// create another specific function
MyFct myf2(sum_wrapper, 10, 2.33/*, add the args of your choice*/);
// create the set
std::set<GenericFunction*> myFcts { &myf1, &myf2 };
// call the functions
for (const auto& f : myFcts)
f->invoke();
return 0;
}
Related
In one part of my code, I have an abstract function type Function which represents any kind of callable and which can be stored in a heterogeneous container, e.g. std::vector<std::unique_ptr<Function>>:
#include <any>
#include <string>
#include <memory>
#include <vector>
#include <functional>
#include <cassert>
class Function
{
public:
Function(std::string name)
: m_name(name)
{}
virtual ~Function(){}
std::string name() {
return m_name;
}
template <typename... Args>
decltype(auto) operator()(Args&&... args)
{
// delegate to invoke, implementation not relevant for question
}
private:
std::string m_name;
// the following is also simplified for the sake of brevity
virtual std::any invoke(std::initializer_list<std::any> const& args) const = 0;
};
template <typename F>
class FunctionImpl : public Function
{
public:
FunctionImpl(F const& f, std::string name)
: Function(name)
, function(f)
{}
private:
std::any invoke(std::initializer_list<std::any> const& args) const override
{
// implementation not relevant for question
return std::any();
}
F function;
};
using FPointer = std::unique_ptr<Function>;
template <typename F>
FPointer make_function(F const& f, std::string name)
{
return std::make_unique<FunctionImpl<F>>(f, name);
}
Now I want to add a function
using FContainer = std::vector<FPointer>;
template <typename F>
bool contains(FContainer const& vec, F const& f)
{
// ?????
}
which returns true, if the function passed as argument in contained in the container, and false otherwise (and probably in a follow-up step a function that returns a reference to the element in the container, if it is contained). How would I write this kind of function? What are my options?
void bar(){}
void foo(){}
struct AClass {
void MemberFunction1(){}
void MemberFunction2(){}
};
struct ACallableClass
{
void operator()(){}
};
int main()
{
FContainer v;
// function pointer
v.push_back(
make_function(
&foo,
"foo"
)
);
// std::function
v.push_back(
make_function(
std::function<void()>(&foo),
"foo"
)
);
// member function
v.push_back(
make_function(
&AClass::MemberFunction1,
"AClass::MemberFunction1"
)
);
// callable
v.push_back(
make_function(
ACallableClass(),
"CallableClass"
)
);
// lambda
v.push_back(
make_function(
[](){},
"empty lambda"
)
);
assert(contains(v, &foo));
assert(contains(v, std::function<void()>(&foo)));
assert(contains(v, &AClass::MemberFunction1));
assert(!contains(v, [](){})); // every lambda is different
assert(!contains(v, &bar));
assert(!contains(v, std::function<void()>(&bar)));
assert(!contains(v, &AClass::MemberFunction2));
return 0;
}
The best solution I could come up with so far was to write a function template
template <typename F> size_t id(F&& id);
that gives a unique id to any kind of callable. Then Function could get a new virtual size_t id() const = 0 method, which would be overwritten by Function<F>. The latter delegates to the free function template. With this, I could compare ids in contains.
I tried implementing the function template using std::hash with function pointers, but I got stuck at hashing member function pointers, callable classes and lambdas. Here is my latest approach: https://godbolt.org/z/zx4jnYbeG.
Sorry for the rather lengthy question. Any help would be greatly appreciated!
EDIT 1:
I can live without std::function support. I would like to support lambdas in principle, but I can live with contains always returning false for lambdas, which makes sense to me. I do want the code to work with function pointers, callable classes and member functions.
EDIT 2:
Here is a working solution based on the suggestions in xryl669s answer: https://godbolt.org/z/vYGesEsKa. std::function<F> and F get the same id, but I suppose this actually make sense, since they are basically equivalent.
Use an unordered_map and not a vector to store your functions.
The key can be derived from the name (probably better anyway), or from the address of the function, but in that case, you'll have an issue with everything that's not a real function (like a method, a std::function<> instance, a lambda, ...)
But since you probably have an issue already with your make_function for methods (you don't capture the instance), you can probably make a specialization for that case using a lambda or a template trampoline and use that address instead.
Another issue to account for is:
std::function<>(&foo) != std::function<>(&foo) (you have 2 instances, they are 2 different objects)
Similarly for lambda functions, two different instance containing the same lambda body won't match anyway.
Compiler is allowed to generate copies of functions if it has all the code for them and it's doing so unless you build with -Os or use external linkage for your functions
So, unless you fallback to a unique identifier that you assign to your Function, you can't assert that a function is identical to another based on the function's body or some instance.
Example (working) godbolt for the specialized template approach: https://godbolt.org/z/8sP5MfG6r
Please notice that you can't store a &foo and std::function<>(&foo) in the container in this approach if using the std::function<>::target() as the key, they'll point to the same function and thus will be overwritten or not inserted since they already exist, but that's probably a good thing for your application it seems.
If you don't care about UB, you can use this version: https://godbolt.org/z/9GoEWMnMb that's reinterpret_cast'ing the function's pointer (and pointer to method too) to use as the hash's key in the map. That's not clean, but since we don't use the result of the cast to call the function, it shouldn't bother much.
I have some code that accepts one type of object and creates another type of object based on the type of the first. (There is a 1->1 relationship between the types.) I originally used a hash table (unordered_map<>) with a key based on the type of the first object to associate a creation function for the second object. But as I am learning more about the C++ features introduced since the last time I was full-time C++, I discovered std::variant<>.
I have successfully converted the implementation to use this C++17 feature. However, there is one remaining piece that is still a bit cumbersome. The design makes a call to a static member function of the second class to validate the contents of the first object, before instantiating an object of the second class. To handle this right now, I'm using a visitor structure with function operators overloaded for each input type.
What I'm wondering is if there is some way to use a template for the association, rather than the copied code with only the types different?
I've tried looking at the way std::variant<> works, and I see where the index of the type can be obtained with .index(). I can see how to instantiate an object based on an index, which I might use if I created a second std::variant<> with the object types. But, as you can see, I don't want to instantiate the object until the parameters have been validated. The function that does that is static, and I don't see a way to associate the parms type with the object type in a way that lets me make the static call.
(I also realize that these two visitor structures can be combined in the code below, but in the real code, the creation is longer and more complicated, and I would rather not have copies of it in each overload.)
struct Type1Parms {};
struct Type2Parms {};
struct Type3Parms {};
...
struct TypeBase {};
struct Type1 : public TypeBase
{
static bool ValidateParms(const Type1Parms&);
Type1(const Type1Parms&);
};
struct Type2 : public TypeBase
{
static bool ValidateParms(const Type2Parms&);
Type2(const Type2Parms&);
};
struct Type3 : public TypeBase
{
static bool ValidateParms(const Type3Parms&);
Type3(const Type3Parms&);
};
...
struct ValidateParmsVisitor
{
bool operator()(const Type1Parms& parms)
{
return Type1::ValidateParms(parms);
}
bool operator()(const Type2Parms& parms)
{
return Type2::ValidateParms(parms);
}
bool operator()(const Type3Parms& parms)
{
return Type3::ValidateParms(parms);
}
...
};
using TypeParms = std::variant<Type1Parms, Type2Parms, Type3Parms, ...>;
struct CreateObjectVisitor
{
std::unique_ptr<TypeBase> operator()(const Type1Parms& parms)
{
return std::make_unique<Type1>(parms);
}
std::unique_ptr<TypeBase> operator()(const Type2Parms& parms)
{
return std::make_unique<Type2>(parms);
}
std::unique_ptr<TypeBase> operator()(const Type3Parms& parms)
{
return std::make_unique<Type3>(parms);
}
...
};
template<typename TParms>
std::unique_ptr<TypeBase> CreateType(const TParms& parms)
{
unique_ptr<TypeBase> obj;
if (visit(ValidateParmsVisitor{}, parms))
obj = visit(CreateObjectVisitor{}, parms);
return std::move(obj);
}
Is there a way to make this association, especially as a type that can be used with a static member function call?
EDIT: I should explain that this is part of a much larger project, with a number of other design criteria that shape its design.
For example, this is for a client interface, where the API is meant to be as simple as can be expressed. The client only has visibility (via header) to the parms structures and a function that takes the parms & returns an object that contains the objects mentioned above. The original design did indeed have a base structure for the parms, which obviously had to be in the public header. However, this meant that a client could inherit from the base class themselves and pass this into the object creation function, or inherit from the acceptable structures. To avoid segfaults, this necessitated adding runtime checks to be sure the types were acceptable, which was mostly handled by the hash design--although it wasn't quite that simple. When I removed the hash design, I also lost this method of type validation, but I recognized that this would be replaced by a compile time check with the variant<>, handling custom structures (no base to check now). I also learned about the C++ version of the final keyword which handled the inheritance issue.
Additionally, while the code above does not show it, the parms structures contain multiple members and the ValidateParms() functions actually attempt to validate whether the values and combinations are valid.
You can create traits for the association:
template <typename T> struct from_param;
template <> struct from_param<Type1Parms> { using type = Type1; };
template <> struct from_param<Type2Parms> { using type = Type2; };
template <> struct from_param<Type3Parms> { using type = Type3; };
Then, you might do
using TypeParms = std::variant<Type1Parms, Type2Parms, Type3Parms>;
std::unique_ptr<TypeBase> CreateType(const TypeParms& parms)
{
if (std::visit([](const auto& param){
return from_param<std::decay_t<decltype(param)>>::type::ValidateParms(parms);
}, parms))
{
return std::visit([](const auto& param) -> std::unique_ptr<TypeBase> {
return std::make_unique<typename from_param<std::decay_t<decltype(param)>>::type>(parms);
}, parms);
}
return nullptr;
}
Demo
or without variant, if you call with correct type:
template <typename T>
auto CreateType(const T& parms)
{
if (from_param<T>::type::ValidateParms(parms))
{
return std::make_unique<typename from_param<T>::type>(parms);
}
return nullptr;
}
There is a very simple method, a set of overloaded functions:
unique_ptr<TypeBase> CreateType(Type1Params const& params)
{
return make_unique<Type1>(params);
}
unique_ptr<TypeBase> CreateType(Type2Params const& params)
{
return make_unique<Type2>(params);
}
unique_ptr<TypeBase> CreateType(Type3Params const& params)
{
return make_unique<Type3>(params);
}
Notes:
You can add another overload to catch other parameters and then return null, but I think a compile-time error would be preferable.
You could also use a template function and specializations, but there's probably little typing to safe that way.
I have class with some calls inside. Every call taking like an argument two callbacks: for successful and error case respectivelly. Inside of these callbacks I have to call for both cases overloaded function with name like "answerCallName", but pass different params to it depending on success.
So with rising a number of such calls it becomes annoying to define for every call two callback inside.
So I'm searching the solution better than "copy paste".
I'm looking on templates. But cannot find any way to use one function name like argument to use it for different overloads inside template.
I've tried to make some templates, but obviously failed, so far as template requeres exect function pointer and in case function is overloaded I need to explicitly show this type.
//========================================================
//Here is exaple of class (library) with a lot of calls
class SomeLargeClass
{
protected:
void callToDoSmth1(std::function<void(int)>, std::function<void(std::string)>);
void callToDoSmth2(std::function<void(char)>, std::function<void(std::string)>);
void callToDoSmth3(std::function<void(const A & a)>, std::function<void(std::string)>);
...
};
//========================================================
//Here is calls I should call when one of callbacks are called. Also this part is placed in the library
class ResponsesClass
{
protected:
void answerCallToDoSmth1(int);
void answerCallToDoSmth1(std::string);
void answerCallToDoSmth2(char);
void answerCallToDoSmth2(std::string);
void answerCallToDoSmth3(const A & a);
void answerCallToDoSmth3(std::string);
...
}
//========================================================
//Here is my class
class MyProxy: public SomeLargeClass, public ResponsesClass
{
...
void action1();
}
//========================================================
//
void MyProxy::action1()
{
auto success = [](int value)
{
ResponsesClass::answerCallToDoSmth1(value);
}
auto error = [](std::string value)
{
ResponsesClass::answerCallToDoSmth1(value);
}
SomeLargeClass::callToDoSmth1(success, error);
}
So I'm looking for something like:
template<class ResponseFn, class ReturnType, class Object>
std::pair<
std::function<void(ReturnType)>,
std::function<void(std::string)>
>
MyProxy::createCallbacks(ResponseFn responseFn, Object object)
//--------------------------------------------------------------------
{
auto onSuccess = [this, responseFn] (ReturnType value)
{
(object->*responseFn)(value);
};
auto onError = [object, responseFn](std::string value)
{
(object->*responseFn)(value);
};
return std::pair<decltype(onSuccess), decltype(onError)>(onSuccess, onError);
}
to create callbacks for every call with one function call.
void MyProxy::actionX()
{
auto callbacks = createCallbacks<int>(&MyProxy::answerCallToDoSmthX); //not working due to diffrent function addresses
SomeLargeClass::callToDoSmthX(callbacks.first, callbacks.second);
}
I'm just intresting could it be solved without makroses and generators.
Is it planned to be resolved in future standarts?
Since C++14 lambdas can have auto parameters:
void MyProxy::action1()
{
auto success_and_error = [=](auto... value)
{
ResponsesClass::answerCallToDoSmth1(value...);
};
SomeLargeClass::callToDoSmth1(success_and_error, success_and_error);
}
This effectively makes the lambda's operator() a variadic template function that takes an arbitrary number of parameters. That way the lambda can implicitly be converted to std::function<void(int)>, std::function<void(std::string)>, std::function<void(std::string, int, float, int, A, B, C)>, and whatever else you like, as long as there is a corresponding overload of SomeLargeClass::callToDoSmth1() that takes the same parameters.
Updates in bold
I am writing a hash function for a table of function pointers with the limitation that the structure of the function pointers and function table cannot be modified (i.e. they have been published to third-parties). Based on Can std::hash be used to hash function pointers?, std::hash can be used for function pointers. Adopting that, it yields the following solution.
The tedious part about this solution is that every time we add new APIs to FuncPointers struct, we'd have to modify the hash specialization to add the corresponding change (i.e. hashFunc(hashedValue, pFuncs->func3) ).
I am wondering if there's a better way to implement this hashing of function pointers so continuous modification to the hash specialization can be avoided?
typedef void (*func_type1) (int);
typedef void (*func_type2) (double);
typedef struct FuncPointers
{
func_type1 func1;
func_type2 func2;
...
} FuncPointers;
template <typename T> void hashFunc (size_t & HashedValue, T funcPointer)
{
std::hash<T> hash;
HashedValue ^= hash(funcPointer); // the XOR operator is randomly picked
}
namespace std
{
template<> struct hash<FuncPointers>
{
size_t operator()(FuncPointers *pFuncs)
{
size_t hashedValue = 0;
hashFunc(hashedValue, pFuncs->func1);
hashFunc(hashedValue, pFuncs->func2);
...
return hashedValue;
}
};
}
Start with this: https://stackoverflow.com/a/7115547/1774667
It provides a hash_tuple::hash<Tuple> that is a valid decent quality hasher (with combining and recursion support!) for a std::tuple.
Next, change FuncPointers as follows:
struct FuncPointers:std::tuple<func_type1, func_type2 /*, ...*/> {
// optional:
func_type1 func1() const { return std::get<0>(*this); }
func_type1& func1() { return std::get<0>(*this); }
//...
};
namespace std {
template<>
struct hash<FuncPointers> {
template<typename... Ts>
std::size_t operator()( std::tuple<Ts...> const& funcs ) const {
return hash_tuple::hash<std::tuple<Ts...>>{}(funcs);
}
};
}
which redirects your std::hash<FuncPointers> to invoke hash_tuple::hash<std::tuple<...>> on the parent of FuncPointers. If you do not want to inherit from std::tuple, changing it to a has-a instead of an is-a relationship should be easy.
The optional func() accessors give you closer to the old interface (just requires a () added), but also adds boilerplate.
An alternative would be:
template<unsigned N>
auto func() const->decltype( std::get<N>(*this) ){ return std::get<N>(*this); }
template<unsigned N>
auto& func()->decltype( std::get<N>(*this) ){ return std::get<N>(*this); }
which changes funcPointers.func1 to funcPointers.func<1>(), but gets rid of tonnes of boilerplate when you add a new func, and stays pretty similar to the old interface of funcPointers.
If there is not much code that is using the old interface, using std::get<N>() makes some sense.
If your names are more descriptive than func1 and you only used that for the example, an enumeration of the function names can be used with std::get or func<X> above. If you go with func<X> you can even make it typesafe (force the use of the named functions).
You'd be better off making your FuncPointers a std::tuple<func_type1, func_type2>. Then see this answer on hashing.
BTW, typedef struct FuncPointers { } FuncPointers is a C-ism which has never been necessary in C++.
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 should be used as a best-practice.
Demonstation of the feature (for pointers):
template <int* Pointer> struct SomeStruct {};
int someGlobal = 5;
SomeStruct<&someGlobal> someStruct; // legal c++ code, what's the use?
Any enlightenment will be much appreciated!
Pointer-to-function:
Pointer-to-member-function and pointer-to-function non-type parameters are really useful for some delegates. It allows you to make really fast delegates.
Ex:
#include <iostream>
struct CallIntDelegate
{
virtual void operator()(int i) const = 0;
};
template<typename O, void (O::*func)(int)>
struct IntCaller : public CallIntDelegate
{
IntCaller(O* obj) : object(obj) {}
void operator()(int i) const
{
// This line can easily optimized by the compiler
// in object->func(i) (= normal function call, not pointer-to-member call)
// Pointer-to-member calls are slower than regular function calls
(object->*func)(i);
}
private:
O* object;
};
void set(const CallIntDelegate& setValue)
{
setValue(42);
}
class test
{
public:
void printAnswer(int i)
{
std::cout << "The answer is " << 2 * i << "\n";
}
};
int main()
{
test obj;
set(IntCaller<test,&test::printAnswer>(&obj));
}
Live example here.
Pointer-to-data:
You can use such non-type parameters to extend the visibility of a variable.
For example, if you were coding a reflexion library (which might very useful for scripting), using a macro to let the user declare his classes for the library, you might want to store all data in a complex structure (which may change over time), and want some handle to use it.
Example:
#include <iostream>
#include <memory>
struct complex_struct
{
void (*doSmth)();
};
struct complex_struct_handle
{
// functions
virtual void doSmth() = 0;
};
template<complex_struct* S>
struct csh_imp : public complex_struct_handle
{
// implement function using S
void doSmth()
{
// Optimization: simple pointer-to-member call,
// instead of:
// retrieve pointer-to-member, then call it.
// And I think it can even be more optimized by the compiler.
S->doSmth();
}
};
class test
{
public:
/* This function is generated by some macros
The static variable is not made at class scope
because the initialization of static class variables
have to be done at namespace scope.
IE:
class blah
{
SOME_MACRO(params)
};
instead of:
class blah
{
SOME_MACRO1(params)
};
SOME_MACRO2(blah,other_params);
The pointer-to-data template parameter allows the variable
to be used outside of the function.
*/
std::auto_ptr<complex_struct_handle> getHandle() const
{
static complex_struct myStruct = { &test::print };
return std::auto_ptr<complex_struct_handle>(new csh_imp<&myStruct>());
}
static void print()
{
std::cout << "print 42!\n";
}
};
int main()
{
test obj;
obj.getHandle()->doSmth();
}
Sorry for the auto_ptr, shared_ptr is available neither on Codepad nor Ideone.
Live example.
The case for a pointer to member is substantially different from pointers to data or references.
Pointer to members as template parameters can be useful if you want to specify a member function to call (or a data member to access) but you don't want to put the objects in a specific hierarchy (otherwise a virtual method is normally enough).
For example:
#include <stdio.h>
struct Button
{
virtual ~Button() {}
virtual void click() = 0;
};
template<class Receiver, void (Receiver::*action)()>
struct GuiButton : Button
{
Receiver *receiver;
GuiButton(Receiver *receiver) : receiver(receiver) { }
void click() { (receiver->*action)(); }
};
// Note that Foo knows nothing about the gui library
struct Foo
{
void Action1() { puts("Action 1\n"); }
};
int main()
{
Foo foo;
Button *btn = new GuiButton<Foo, &Foo::Action1>(&foo);
btn->click();
return 0;
}
Pointers or references to global objects can be useful if you don't want to pay an extra runtime price for the access because the template instantiation will access the specified object using a constant (load-time resolved) address and not an indirect access like it would happen using a regular pointer or reference.
The price to pay is however a new template instantiation for each object and indeed it's hard to think to a real world case in which this could be useful.
The Performance TR has a few example where non-type templates are used to abstract how the hardware is accessed (the hardware stuff starts at page 90; uses of pointers as template arguments are, e.g., on page 113). For example, memory mapped I/O registered would use a fixed pointer to the hardware area. Although I haven't ever used it myself (I only showed Jan Kristofferson how to do it) I'm pretty sure that it is used for development of some embedded devices.
It is common to use pointer template arguments to leverage SFINAE. This is especially useful if you have two similar overloads which you couldn't use std::enable_if default arguments for, as they would cause a redefinition error.
This code would cause a redefinition error:
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
void foo (T x)
{
cout << "integral";
}
template <typename T, typename = std::enable_if_t<std::is_floating_point<T>::value>>
void foo (T x)
{
cout << "floating";
}
But this code, which utilises the fact that valid std::enable_if_t constructs collapse to void by default, is fine:
// This will become void* = nullptr
template <typename T, std::enable_if_t<std::is_integral<T>::value>* = nullptr>
void foo (T x)
{
cout << "integral";
}
template <typename T, std::enable_if_t<std::is_floating_point<T>::value>* = nullptr>
void foo (T x)
{
cout << "floating";
}
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.