Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

actual function as template parameter?

Tags:

c++

templates

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.

like image 866
lezebulon Avatar asked Feb 13 '23 19:02

lezebulon


1 Answers

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.

like image 178
AnT Avatar answered Feb 15 '23 10:02

AnT