Consider this hypothetical code snippet :
template<?? function>
void loop() {
for(int i =0; i < 10000; ++i ) {
function(i)
}
}
//...
void print(int i) {
std::cout << i << '\n';
}
//...
loop<print>();
is it possible to do something like that in C++ ? So far I know that function pointers and generic functors can be passed through templates parameters (like in std::sort), but is there a way to make it so that no actual object is passed during runtime and the call to "print" is completely direct (ie no indirection) ? ie transferring the actual function by "value" in the template, like it's possible to pass integer in a template using template <int i>
or some other integral types.
Of course, it is possible. Template non-type parameters can be of function pointer type. In the most simplistic case, specifically tailored to your simple example it might look as follows
template <void (*function)(int)>
void loop() {
for(int i = 0; i < 10000; ++i ) {
function(i);
}
}
Note that C++03 stated that a valid template argument for such template must be a pointer to a function with external linkage. C++11 removed the external linkage requirement.
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