Pointer To Member Functions, Is This Kind of Use SAFE?

  • Permalink
  • submit to reddit
  • Email
  • Follow


Hi All,

I am implementing a framework. In my framework, I want to define a set of 
handler classes,
deriving from a common base class. Then in the handler classes, I would like 
to define a
set of handler functions, all have the same signature, to say, all have the 
signature like:
void f(void *)

Then in another loop, I would instantiates those handlers and dynamically 
choose a handler
function in a handler class to fulfill a task. Since the concrete handler 
and the name of the
handler functions cannot be pre-determinated, I would like to pass in a 
pointer to the object
of a handler class and a pointer to member function to the caller, thus in 
the caller, I could
compose those two pointers up to call the desired handler function.

The problem, is then, how could I achieve this under a unified interface? I 
defined a pointer
to member function type in the Base class scope and try to assign pointer to 
derived class's
member functions to variable of this type. Although I have tried this in 
both G++ 3.2 and VC7,
I still doubt if such trick is safe, anybody could give me some suggestions 
and hints? And
I would appreciate all of your helps.

Following is a sample code I have used for test under G++ and VC7. Thanks in 
advance.

#include <iostream>
using namespace std;

class Base{
public:
  Base(){}
  virtual ~Base(){}

  virtual void v() = 0;
};

typedef void (Base::*MemberFunc)(void);

class Derived1 : public Base{
public:
  void f(){
    cout << "This is in f." << endl;
  }

  void g(){
    cout << "This is in g." << endl;
  }

  void v(){
    cout << "This is in Derived1: v." << endl;
  }
};

class Derived2 : public Base{
public:
  void h(){
    cout << "This is in h." << endl;
  }

  void m(){
    cout << "This is in m." << endl;
  }

  void v(){
    cout << "This is in Derived2: v." << endl;
  }
};

class Leaf : public Derived2{
public:
  void n(){
    cout << "Hello, world, in n." << endl;
  }

  using Derived2::v;
};

int main(){
  MemberFunc fp;
  Base *pBase;

  Derived1 d1;
  Derived2 d2;
  Leaf l;

  cout << "Test Derived1 ..." << endl;
  pBase = &d1;
  fp = static_cast<MemberFunc>(&Derived1::f);
  cout << "fp to Derived1::f is: " << fp << endl;
  (pBase->*fp)();

  fp = static_cast<MemberFunc>(&Derived1::g);
  cout << "fp to Derived1::g is: " << fp << endl;
  (pBase->*fp)();

  fp = static_cast<MemberFunc>(&Derived1::v);
  cout << "fp to Derived1::v is: " << fp << endl;
  (pBase->*fp)();


  cout << "Test Derived2 ..." << endl;
  pBase = &d2;
  fp = static_cast<MemberFunc>(&Derived2::h);
  cout << "fp to Derived2::h is: " << fp << endl;
  (pBase->*fp)();

  fp = static_cast<MemberFunc>(&Derived2::m);
  cout << "fp to Derived2::m is: " << fp << endl;
  (pBase->*fp)();

  fp = static_cast<MemberFunc>(&Derived2::v);
  cout << "fp to Derived2::v is: " << fp << endl;
  (pBase->*fp)();

  cout <<"Test Leaf ..." << endl;
  pBase = &l;
  fp = static_cast<MemberFunc>(&Leaf::n);
  cout << "fp to Leaf::m is: " << fp << endl;
  (pBase->*fp)();

  fp = static_cast<MemberFunc>(&Leaf::v);
  cout << "fp to Leaf::v is: " << fp << endl;
  (pBase->*fp)();

  return 0;
}


=============================
output:
=============================
Test Derived1 ...
fp to Derived1::f is: 1
This is in f.
fp to Derived1::g is: 1
This is in g.
fp to Derived1::v is: 1
This is in Derived1: v.
Test Derived2 ...
fp to Derived2::h is: 1
This is in h.
fp to Derived2::m is: 1
This is in m.
fp to Derived2::v is: 1
This is in Derived2: v.
Test Leaf ...
fp to Leaf::m is: 1
Hello, world, in n.
fp to Leaf::v is: 1
This is in Derived2: v.

========================================
BTW: it's queer that the output of "fp to XXXX is:" lines are always 1,
both in output of G++ and VC. Anybody could explain this to me? 



      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Neal 11/18/2004 12:08:29 AM

See related articles to this posting


Neal Chen wrote:

 > Hi All,
 >
 > ...
 >
 > ========================================
 > BTW: it's queer that the output of "fp to XXXX is:" lines are always 1,
 > both in output of G++ and VC. Anybody could explain this to me?
 >

  cout << "fp to Leaf::v is: " << fp << endl;

should be

  cout << "fp to Leaf::v is: " << (void *)fp << endl;

printing function pointer using ostream will always give output '1'

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply syro555 11/19/2004 4:54:44 PM

"Neal Chen" <zeusnchen@msn.com> wrote in message news:<cnfipp$vs4$1@news.yaako.com>...
 > Hi All,
..............
 > The problem, is then, how could I achieve this under a unified interface? I
 > defined a pointer
 > to member function type in the Base class scope and try to assign pointer to
 > derived class's
 > member functions to variable of this type. Although I have tried this in
 > both G++ 3.2 and VC7,
 > I still doubt if such trick is safe, anybody could give me some suggestions
 > and hints? And
 > I would appreciate all of your helps.

Well, static_cast works in this case?
if you are sure that object and function
pointers matches right type, then it is safe.

Greetings, Bane.

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply bmaxa 11/19/2004 4:55:52 PM
comp.lang.c++.moderated 10662 articles. 10 followers. Post

2 Replies
199 Views

Similar Articles

[PageSpeed] 35


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Calling member function using a smart pointer and a pointer to member function
/* I'm trying to figure out how to call a class member function using a pointer to the member function and either a real pointer to the class or a smart pointer to the class. So far, I've been unable to find the syntax that I need. I have hacked together a solution that I think I could use, and that doesn't require that syntax, but the solution is unlovely and I'd much prefer to find the syntax. There is one significant constraint: I want to use operator ->() in the smart pointer, because I intend to exploit the "temporary's lifetime benefit." If I c...

Pointer to Member Function used in member function
Hi, Would you kindly advise me how to write pointer to member function, used in a member function as shown below: Class A { public: void f(){ void(*k)() = g;} // ok void f1(){ void(*k)() = g1;}// error private: static void g(){} void g1() {} }; g() is a static function and pointer to the funcion can be used in f(), but this is not satisfuctory for my purpose, becasue static g() is not allowed to use non-static member data in the class. I whould like to use pointer to non-static member function in f1(). I do not know how to do so. Thank you for your time. My compiler is MC++6. ...

pointer to member function and pointer to constant member function
Are these pointers the same? Fraser. On Sat, 14 Aug 2004 12:16:12 +0100, "Fraser Ross" <fraserATmembers.v21.co.unitedkingdom> wrote: >Are these pointers the same? No. Try this: #include <iostream> #include <ostream> using namespace std; class A { public: void func() { cout << "Non-const func()." << endl; } void func() const { cout << "Const func()." << endl; } }; typedef void (A::* pf)(); typedef void (A::* cpf)() const; int main() { A a; const A b; pf fp = &A::func; cpf cfp = &a...

What is the correct grammar to make a function call by using static member data which is a pointer to a ordinary class member function?
I have class member data which is a pointer to class member function. However, I'm fail to compile the code. What is the correct grammar to make a function call by using static member data which is a pointer to a member function? class Test { public : typedef int (Test::*pfnOperate)(int x, int y); static const pfnOperate m_arpOperate[2]; public : int Add(int x, int y); int Subtract(int x, int y); void Foo(); }; const Test::pfnOperate Test::m_arpOperate[2] = {Test::Add, Test::Subtract}; int Test::Add(int x, int y) { return x + y; } int Test...

using and de-referencing a function pointer in a member function
Hi everyone, I'm trying to execute the same function call with 1 parameter different in a switch statement of a member function. However, if a certain condition is true (and I can check that before the switch statement), I want to execute a difference function call with the same parameters. So instead of using an if-clause to distinguish the 2 cases in each case-statement, or doubling the switch, I considered this: void configuration::add (string param, configParameter cp); void configuration::set (string param, configParameter cp); my member function: void configuration::add (str...

Better way to call member function using function pointer?
Hi, Following is isolated code reproducing the issue I encountered while using function pointers: ////////////////////////////////////////////// #include <iostream> #include <string> #include <map> using namespace std; class Sample { public: Sample() { funPtrs["fun1"] = &Sample::fun1; funPtrs["fun2"] = &Sample::fun2; funPtrs["fun3"] = &Sample::fun3; } void process() { string str[] = { "fun1", "fun2", "fun3" }; // Method 1 - Compilation error. for (int i = ...

Pointer to a pointer to a pointer to a member function
Hi, I'm having a problem compiling the following snippet with MSVC++ 7.1 and I'm not sure if it is a compiler bug? (or I am being stupid) struct Vector3 { float x, y, z; }; void blah() { static Vector3 (Vector3::*function)(float); static Vector3 (Vector3::**_function)(float) = &function; /*static*/ Vector3 (Vector3::***__function)(float) = &_function; *__function = &function; } If I uncomment the 'static' qualifier it then compiles fine? (Or if I change the return type of the function pointers to an atomic type such as &#...

member function calling member function through pointer
I want to call from inside a member function another class member function through a member function pointer (without having to create an instance of the class) However the following class definition does not compile (Borland). Error: calling of nonfunction. Playing around with * and & doesnot help. I am probably doing something wrong. Ad class A { typedef int (A::*Ptr)(); Ptr ptr_; int F1() {return 1;} void F2() { int i = F1(); ptr_ = &A::F1; int j = ptr_(); // error calling of nonfunction. } }; [ See http://www.gotw.ca/resources/clcm.htm fo...

function pointer and member function pointer question
Okay, I know that a function pointer and member function pointer have different types. Is it kosher to convert a member function pointer to a regurlar function pointer (with the same parameters)? I have a measurement class, and I'd like to be rather general, so store function pointers for get operations. Can I typecast a member fuction pointer and pass it to the class? I know the FAQ disucusses this a bit, but I can't infer the answer from it. Thanks, Glen "glen stark" <mail@glenstark.org.nospam> wrote in message news:3f86869a$1@pfaff2.ethz.ch... > Ok...

How can I use a function pointer to non-static member function of a class.
Hi All, Except function pointer to a static member funciton of a class (or a function). As the following code, I could pointer a non-static member function of a class. And "Equal" was printed, the pointer has meaning. But how can I use it?? I.e., I'd like to call the member method by using the function pointer (like using c function pointer). class TMyClass { public: int DoIt(float a, char b, char c){ ... }; } int (TMyClass::*pt2Member)(float, char, char) = NULL; pt2Member = &TMyClass::DoIt; // C++ if(pt2Member== &TMyClass::DoIt) cout << "Equal&quo...

Member function pointer to member function of another class
Hi, I'm having huge syntax problem dealing with function pointers. Here's what I'm doing: I have 2 classes, ClassA and ClassB. ClassA owns an instance of ClassB. What I want to do is pass a function pointer to a member function of ClassB as a parameter to a member function of ClassA. I don't want ClassA's member function to call ClassB's function directly because ClassA can be used in 2 ways, one of which is a case in which it does not create an instance of ClassB; hence by passing a function pointer I can handle that case easily. This is the code I have: class Class...

Member function pointers to member functions with default arguments
Hi, The following doesn't compile (using g++ 4.0.3 with all warnings, - pedantic, -ansi, etc.): class X { public: int f(int i = 0) { return i; } }; int main() { int (X::*blah)() = &X::f; // Invalid conversion. X x; return (x.*blah)(); } I always thought that specifying default arguments (like above) was a kind of shorthand for something like: class X { public: int f(int i) { return i; } int f() { return f(0); } }; int main() { int (X::*blah)() = &X::f; // Okay now. X x; return (x.*blah)(); } Is there a way to g...

Function pointer member variable to non-member function
I have a class that has an array of function pointers as a member variable. I pass in function pointers in the constructor (these function pointers are to C functions). Later when I try and call the function, it says there is an error and my program crashes (assuming a memory problem). Here is a small example of what I am trying to do. ----- Common include file ------ typedef int (*ptrFunc)(int); ----- Separate .h/.cpp -------- class A { public: A( ptrFunc one, ptrFunc two ); void UseFuncs(); private: ptrFunc m_pFunctions[2]; } A::A( ptrFunc one, ptrFunc...

static member functions vs. member function pointers
Hi, I have seen the use of static member functions for callbacks by passing the name of the static member function and the this pointer to the code that will call back. I was thinking the same can be achieved by using member function pointers and the this pointer. E.g. void FuncThatWillCallback( MyClass::staticFunc, (void *)this) { staticFunc(this); } void FuncThatWillCallback( PtrToMemberFunc, (void *)this) { this->PtrToMemberFunc; } Is there a reason why the static member function trick is so widely used? (Except when FuncThatWillCallback is part of a 3rd party lib). * paul: &...

Using a pointer to member function
Hello. I'm trying to make a sort of generic integral class, holding the boundary values and the integrand. Eventually I'd like to use it inside a class, like the example below. I think the problem is that in order to pass a member function, I have to qualify the name a bit differently, for example: typedef double (astro::universe::*pfn)(double); (by the way, I don't think this actually worked...) But doing this sort of thing of course doesn't make the integral class generic enough. I'd like to get some advices as to how I can make such an integral class that even a m...

Elegant solution for pointer-to-a virtual member function to function pointer
Hello, I would like to see a cleaner solution than the one I have written in the example below for passing a pointer-to-a-virtual member function of an abstract class to a function pointer. /* * Suppose this is the interface provided as API by an external library * written in C, containing the pointer to a function to be called by * the library itself. */ struct S { void *o; void (*callback)(S* p); }; #include <iostream.h> /* * This is my abstract class with the virtual member function. */ class A { public: virtual void f() = 0; ...

pointer-to-member data and pointer-to-member functions and access specifiers
Hi I having been trying to find if pointer-to-member data and pointer-to-member functions are subject to access specifiers in any way (public, private or protected) and so far have drawn a blank. Are they subject to or not subject to access specifiers? Thanks Stephen Howe On Monday, 5 November 2012 01:24:22 UTC+2, Stephen Howe wrote: > Hi > > I having been trying to find if pointer-to-member data and pointer-to-member > functions are subject to access specifiers in any way (public, private or > protected) and so far have drawn a blank. > > Are t...

Pointer-to-member-function pointing to a member function of an inherited class
The subject basically says what I am having trouble with. For an example lets say I have a class A which has a function f. I then also have a class B which inherits from A and has a function g. class A { public: void f(int,float); }; class B : public A { public: void g(int, float); }; Okay, now with all that setup, if I created a pointer to a member function something like this: typedef void (A::*MFP)(int a, float b); if I then use it such as MFP mfp = &A::f; then everything works fine. even if I do: MFP mfp2 = &B::f; then everything still works (presumably because f is n...

Function pointer member variable to non-member function #2
I have a class that has an array of function pointers as a member variable. I pass in function pointers in the constructor (these function pointers are to C functions). Later when I try and call the function, it says there is an error and my program crashes (assuming a memory problem). Here is a small example of what I am trying to do. ----- Common include file ------ typedef int (*ptrFunc)(int); ----- Separate .h/.cpp -------- class A { public: A( ptrFunc one, ptrFunc two ); void UseFuncs(); private: ptrFunc m_pFunctions[2]; } A::A( ptrFunc one, ptrFunc two ) { m_pFunctions[0] = one; m_p...

Passing a pointer to member function as a parameter to another member function
Gurus, I have the following implementation of a member function: class A { // ... virtual double func(double v); void caller(int i, int j, double (* callee)(double)); void foo() {caller(1, 2, func); } The compiler told me there's a syntax error, because the pointer to a member function is different from a pointer to a regular function. That is, the func cannot be passed to caller. I checked the FAQ and in "[30] Pointers to member functions", it says the pointers to a member function and to a regular member function are different. Ok, then I tried to change it to static, and it...

Use of member function pointers & this
Stupid question, probably, but: In this class struct A { typedef void (A::*callback)(); callback f; void doit() { (*f)(); } } the compilers we use give an error along the lines of "must use ->* or ..* with member function pointer" and we have to write (this->*f)(); Why, in a class, is it necessary to specify the this-> part? Actually, I'd like to know why is it necessary to specify the * and the brackets as well? The only way this compiles is if you specify (this->*f)() any other variant, such as *f(), f(), this->*f(), fail wit...

using function pointer class members.
Hi, I am having a CPP file which defines a class: class xyz{ public: int (*funcptr)(void); } A function foo is defined in a "C file" and in the CPP file, I need to make an assignment funcptr = foo; So I declared foo as extern "C" in the CPP file: extern "C" int foo(void); But I am getting an error in the assignment, since one side is of type "extern C". What is the solution for this? Please do help. TIA. -- jag. "Quaerendo invenietis" <jagadeeshbp@gmail.com> wrote in message news:1131618875.121857.194360@g14g2000cwa....

Passing pointer to member function to different member function that then calls for_each
Ok, this is what I am trying to do. I have a member function that as a parameter accepts a pointer to a different member function. In this 2nd function, I want to iterate over an STL container and call the passed in member function. I can do this in my own loop, but I am looking to call for_each. I am a little confused on the syntax to use. Any help would be appreciated. look at the following code and at the comment in the printHold function thanks in advance #include <iostream> #include <vector> #include <string> typedef std::vector<std::string> Holder; cla...

Using (return val of) member function as default parameter of member function
Hello. Is it not possible to use (the return value of one member function) as default value for a parameter in another member function of the same class? For example In the code below I was suprised to get the compiler error "error: cannot call member function �tBcPins* tBcPinMan::allPins()� without object" If its not possible is there any decent "hack" or alternative to do achieve the same. Thanks very much in advance class tBcPinMan { ....... void fillLevelMainFromAux(tBcPins * Pins = allPins()); tBcPins * allPins(); }; -- [ See http://www.gotw.ca...