Re: Explicit function vs. overloaded operator?
From: Siemel Naran (SiemelNaran_at_REMOVE.att.net)
Date: 05/27/04
- Next message: John Harrison: "Re: Inheritance problem ...whats next?"
- Previous message: David: "Inheritance problem ...whats next?"
- In reply to: BCC: "Explicit function vs. overloaded operator?"
- Next in thread: Jeff Schwab: "Re: Explicit function vs. overloaded operator?"
- Reply: Jeff Schwab: "Re: Explicit function vs. overloaded operator?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 27 May 2004 04:08:38 GMT
"BCC" <bryan@akanta.com> wrote in message news:t59tc.73289
> In looking through some code I have inherited, I notice a lot of places
> where the programmer used operator() as a function call:
> void operator() (int x, int y);
>
> Rather than an explicit function name:
> void MyFunction(int x, int y);
Does he pass MyFunction objects to a template? Something like this:
template <class Iter1, class Iter2, class Action>
void for_each(Iter1 begin1, const Iter1 end1, Iter2 begin1, Action action) {
for ( ; begin1!=end1; ++begin1, ++begin2) action(*begin1, *begin2);
}
If yes, then it makes sense to write an operator(), as the template for_each
requires it. But then again we could have written for_each to call
action.MyFunction(*begin1, *begin2).
The technical advantage of operator() is that Action can be either a class
object with an operator() or a simple function. If a function, then the
type of Action is something like void (*)(int, int).
The conceptual advantage is that if class MyClass does just one thing, then
operator() reflects this one thing, and thus the essence of the class. But
I think this is a matter of style. Having an explicit function name might
make the code easier to read. For example, style.Combine(1, 2) is usually
easier to read and understand in code reviews than style(1, 2).
> Then when he instantiates a class he calls it:
> MyClass myclass;
> myclass (x, y);
Please note you can say MyClass()(x, y), though not sure if this notation is
in popular usage.
> vs.
>
> MyClass myclass;
> myclass.MyFunction(x, y);
>
>
> Is there any advantage to this or is it just a style?
My guess it's a matter of style.
- Next message: John Harrison: "Re: Inheritance problem ...whats next?"
- Previous message: David: "Inheritance problem ...whats next?"
- In reply to: BCC: "Explicit function vs. overloaded operator?"
- Next in thread: Jeff Schwab: "Re: Explicit function vs. overloaded operator?"
- Reply: Jeff Schwab: "Re: Explicit function vs. overloaded operator?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|