Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Passing Functions by value or reference

26 views
Skip to first unread message

Doug Mika

unread,
May 4, 2015, 12:15:42 PM5/4/15
to
I wish to pass a function into another function, so I decided to use templates for this purpose, ie:

template<typename SortFunc>
void Algorithm(SortFunc mySortFunc){
//Code goes in here
}

template<typename SortFunc>
void Algorithm(SortFunc& mySortFunc){
//Code goes in here
}

the question is, when I call Algorithm with my sort function name (NOT a functor BUT a function defined in the program), would it matter if Algorithm takes my sort function by reference or by value?

To put it simply, when passing functions (NOT functors), what is the difference between passing these by value or by reference?

Thanks
Doug

Victor Bazarov

unread,
May 4, 2015, 12:29:42 PM5/4/15
to
Most likely it would not matter if you're passing your functions to
those templates by means of the name of the function, like

Algorithm(mySpecialSort);

. When used, the reference to function probably (just like a "real"
function) decays into a pointer to function, or, if simply called,
behaves just like a function would do. The difference between a pointer
to function versus a reference to it is that a pointer to function *can*
be null, and needs to be checked for that, I think. A reference to
function should always be initialized to something, so it's likely not
to require checking. That's my understanding.

V
--
I do not respond to top-posted replies, please don't ask

Richard

unread,
May 4, 2015, 1:26:04 PM5/4/15
to
[Please do not mail me a copy of your followup]

Doug Mika <doug...@gmail.com> spake the secret code
<a0a59585-f423-408d...@googlegroups.com> thusly:

>To put it simply, when passing functions (NOT functors), what is the
>difference between passing these by value or by reference?

Passing function names by value implies that they could potentially be
nullptr. Passing function names by reference means that they can
never be referring to a non-existing function.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
0 new messages