Consider this code (godbolt):
#include <iostream>
template<typename F> void call_by_val(F funct)
{
std::cout << "call_by_val(): ";
funct();
}
template<typename F> void call_by_ref(F& funct)
{
std::cout << "call_by_ref(): ";
funct();
}
template<typename F> void call_by_cref(const F& funct)
{
std::cout << "call_by_cref(): ";
funct();
}
void free_funct()
{
std::cout << "free_funct()\n";
}
int main()
{
call_by_val( free_funct );
call_by_ref( free_funct );
call_by_cref( free_funct );
}
All of these three calls work as expected. In case of a free function I'm not sure what's happening under the rug, so I'm wandering what's the difference in these three styles, semantically speaking. Is there an objective reason to prefer one over the others?
funct = some_other_function;
would do in each case – AlbemarleF
should bevoid (*)()
. Passing a pointer by reference only makes sense if you want to change the pointer inside the called function. – Twitterycall_by_*()
, a pointer? – SpringletF
as a pointer, right? In this case maybe(const F funct)
would make sense if meant const pointer to function – Springlet