mem_fun_ref

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Anders

    mem_fun_ref

    Hello.
    If I was to call a method of class T, M for each element in a collection,
    I'd do it like this:

    vector<int> vec;
    ....
    for_each(vec.be gin(), vec.end(), mem_fun_ref(&T: :M));

    Okay, I can see that mem_fun_REF makes it obvious that I must use a
    reference, but why? Is it not possible to pass a function by-reference? As I
    see it, T::M is being passed as a pointer here.

    void func(int& val); func(12); << reference
    void func(int* val); int val = 12; func(&val); << pointer

    //Anders


  • Kurt Krueckeberg

    #2
    Re: mem_fun_ref

    [color=blue]
    > Hello.
    > If I was to call a method of class T, M for each element in a collection,
    > I'd do it like this:
    >
    > vector<int> vec;
    > ...
    > for_each(vec.be gin(), vec.end(), mem_fun_ref(&T: :M));
    >
    > Okay, I can see that mem_fun_REF makes it obvious that I must use a
    > reference, but why? Is it not possible to pass a function by-reference?[/color]

    No, you can only pass the address.[color=blue]
    > As I see it, T::M is being passed as a pointer here.[/color]

    The REF, in mem_fun_ref, refers to the argument type( of T::M ), which
    will be passed to the function call operator.[color=blue]
    >
    > void func(int& val); func(12); << reference
    > void func(int* val); int val = 12; func(&val); << pointer
    >
    > //Anders
    >
    >[/color]


    Comment

    • tom_usenet

      #3
      Re: mem_fun_ref

      On Mon, 30 Jun 2003 22:34:24 +0200, "Anders" <gregersen@adsl home.dk>
      wrote:
      [color=blue]
      >Hello.
      >If I was to call a method of class T, M for each element in a collection,
      >I'd do it like this:
      >
      >vector<int> vec;
      >...
      >for_each(vec.b egin(), vec.end(), mem_fun_ref(&T: :M));[/color]

      That can't be legal - you can't call a T member function on an int
      reference.
      [color=blue]
      >
      >Okay, I can see that mem_fun_REF makes it obvious that I must use a
      >reference, but why? Is it not possible to pass a function by-reference? As I
      >see it, T::M is being passed as a pointer here.
      >
      >void func(int& val); func(12); << reference
      >void func(int* val); int val = 12; func(&val); << pointer[/color]

      The ref refers to the the fact that the object passed as the first
      argument of the functor must be a reference. e.g.

      T t;

      mem_fun_ref(&T: :M)(t); //pass T reference

      mem_fun(&T::M)( &t); //pass T pointer

      so in practice you use mem_fun_ref for containers like:
      vector<T>
      and mem_fun for containers like:
      vector<T*>

      Tom

      Comment

      Working...