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 10658 articles. 9 followers. Post

2 Replies
193 Views

Similar Articles

[PageSpeed] 31


  • 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. ...

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 = ...

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...

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...

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....

Using member function pointers as template arguments
I'm trying to convert a construct like this: template <class R, class T> struct Foo { Foo(R (T::*m)) : member(m) {} R T::*member; }; template <class R, class T> Foo<R, T> makeFoo(R (T::*m)) { return Foo<R, T>(m); } struct S { int a; }; makeFoo(&S::a); into something where the member pointer is a template parameter: template <class R, class T, R (T::*member)> struct Foo {}; template <class R, class T, R (T::*member)> Foo<R, T, member> make Foo() { return Foo<R, T, member>(); } struct S { ...

Possible to use varags with member-function pointers?
Has anyone ever successfully implimented passing member-functions to a varargs function? I thought it would be fairly straight-forward, but seems to come up with nice syntax errors. I've checked my code for syntax errors, so it must be something with my code effecting the code returned by the va_arg macro. I'm implimenting a recursive-decent parser, and I need to make a varargs function that is passed a variable number of productions owned by the same class, terminated by a NULL. The function-pointers are of type "CNode* (CParser::*)(CTokenList*)" Here's my code: CNode...

proper way to save/use pointers to member functions?
I have some old code that has worked on every compiler I have tried until now. XCode 2.2 is complaining that ISO C++ forbids what I am trying to do, and I'm wondering if there is a work-around for this. (incidentally, if any of you recall the ViewKit Motif wrapper created by SGI, this technique was borrowed from its callback mechanism) I have a base class that is used for objects that can call and "receive" callback functions. I have the concept of a "CallbackMethod" which is the signature of a member function that can be used to receive such "events"...

non-virtual call to a virtual function using pointer to member
Hi. for example i have base class A and dirved class B: struct A { virtual void f() { std::cout << "A::f()" << std::endl; } }; struct B : public A { void f() { std::cout << "B::f()" << std::endl; } }; int main() { B b; A *a = &b; a->f(); // virtual call. calls B::f() a->A::f(); // non-virtual call. calls A::f() A::* pf; pf = &A::f(); (a->*pf)(); // virtual call. calls B::f() pf = /* ??? */; // what should i write here for desired effect(non- virtual call) (a->*pf)(); // non...

Pointer to member function
I have class that contains a member function that is to be implemented as a task. This task is a 'receive message' type of task that will pend until receipt of a message. It determines the message type and then call the appropriate function in the appropriate class to process the message. I need to get a pointer to this member function but do not want to have to declare my pointer as static. Actually, if someone can help me out here with an understand of what that would mean relative to my example. I understand what static means but books have eluded to the fact that data that a stati...

Can't use pointer to member function inside main()?
My code may sound strange. I define pF inside class. pF is a pointer to member function. You can choose one of three member function's memory address and put it into pF. Only one member function as F() is able to invoke pF, but you can't invoke pF inside main(). To reduce CPU's overhead so you don't need to invoke F() and you can invoke pF directly. Take a look at my code. Please forgive me if you complain that my post is not wrapped with single line. I have no control to post using Google newsgroups. class Test { public: Test() { } ~Test() {} void F1() { pF = &...

C++ error using non-type template argument of member function pointer defaulted to 0
The code: template <typename C, void (C::*g)() = 0, void (C::*s)() = 0> struct ATemplate { }; struct TestBugClass { void AFunc() {} ATemplate<TestBugClass,&TestBugClass::AFunc,0> inst; }; Under VC9 this compiles without error but Comeau online gives me: "ComeauTest.c", line 1: error: argument of type "int" is incompatible with template parameter of type "void (C::*)()" template <typename C, void (C::*g)() = 0, void (C::*s)() = 0>" etc. I see nothing wrong with initializing a member function non-type template parameter t...

error: must use '.*' or '->*' to call pointer-to-member function in '__unary_op (...)'
hi! a little compiler error. pls help. class A{ B get(unsigned int i);// return an B object whose state depend on *this and i std::vector<B> get_vec(){ std::vector<unsigned int> ints(n); iota(ints.begin(),ints.end(),0); std::vector<B> ret; transform( ints.begin(), ints.end(), back_inserter(ret), get//or &get, *this.*get etc... ); return ret; }; private: unsigned int n; } In function '_OutputIterator std::transform(_InputIterator, _InputIterator, _OutputIterator, _UnaryOperation) [with _InputIterator = __gnu_cxx::__normal_ite...

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...

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...

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...