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

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
Neal
11/18/2004 12:08:29 AM
comp.lang.c++.moderated 10707 articles. 0 followers. allnor (8507) is leader. Post Follow

2 Replies
224 Views

Similar Articles

[PageSpeed] 1
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
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
bmaxa
11/19/2004 4:55:52 PM
Reply:
Similar Artilces:

some problem about the target functions for opmization(lsqnonlin and fminunc)
Dear all, I meet some tricky problems when I apply the Matlab function lsqnonlin. I hope you would like to help me. %% First question: For example, I have created my target funtion in an m file already, I apply lsqnonlin to find [sigma,phi] such that argmin [F(1)^2+F(2)^2]: function [F]= myfun(x) sigma=x(1); phi=x(2); F(1)=sigma^phi; F(2)=sigma*phi; end; However, it seems that matlab cannot work properly, which is cause by my defining sigma=x(1) and phi=x(2). Obviously, one could solve this by defining F(1) and F(2) by using x(1) and x(2) direcly without introducing sigma...

Minix Blocking Servers Using receive()
Hello! I was wondering how it might be possible to setup a Minix server process that blocks on receive()? I checked the source code used for several of the Minix servers that are supplied with Minix 3.0, and the only thing I could think to do was #define _SYSTEM. Nothing else I found in the source code of any of the servers gave me any insight, but is there something I missed? Right now, I have a user-space process that does a busy-loop receiving data from receive() and printing information about the message to stdout. It appears to be using a non-blocking form of receive, but I want it t...

Pointer to pointer #2
hi friends, don't understand this: /* **p is a pointer to *a[], but if *a stops increasing when reads abc, where is pointing *p?? */ #include <stdio.h> int main(void) { char *a[] =3D {"abc", "def", "ghi", "jkl", NULL}; char **p; p =3D (char **)a; while (*p) { while (**p) { printf("*a=3D%p *p=3D%p %c %s\n", *a, *p, **p, *p); (*p)++; } p++; } return 0; } /* Returns david@debian:~$ ./demo *a=3D0x4005ec *p=3D0x4005ec a abc *a=3D0x4005ed *p=3D0x4005ed b bc *a=3D0...

Using FSLETTER
Under MVS environment, For using a FSLETTER procedure, is there a way to create the Letter via batch rather than using the SAS online screens ? I have a letter in a text file and I would like to load the letter to the SAS catalog dynamically via batch whenever the letter changes. Any help in this regard will be appreciated.. thanks Vijay ...

Using Subversion
Having thought about STS on the other thread and figuring that I should try using Subversion a bit more I'm giving it a spin, but am a little unsure about how all the bits fit together and whether they make sense anymore? I can see what using PAX does - but am not sure why I need to use it? What does having all the classes in seperate files really do for me - as a decent merge tool quite happily resolves all conflicts in a big file quite easily (this could be me being naive - haven't encountered big merges in my experiements). The TortoiseSVN tool - really has a great diff...

SAP PRA Consultant Functional Technical
Posted from http://www.workinsight.com. Go to that web site search for Job: A634560 or for more information OR CLICK on the link (http://workinsight.com/j/fmpro?-db=jobs.okt&-lay=we&-format=m&job+id=A634560&-find= Job Description Follows W 2 CONTRACT ONLY Extensive exploration and production accounting experience with a minimum of 5 7 years experience in a upstream ERP Systems development and support A concentration of 3 years minimum experience in SAP PRA is required with strong functional technical knowledge in the areas of ownership production regulatory reporti...

A scan function question
I have the following variable (date) as below: Date ----- 25Dec2006 02Jan2009 15Feb2009 18Nov2004 Now if I want to get only the day fom the above values and want those values to a new varibale (Day) as below: Day --- 25 02 15 18 Shoudl I use scan function to get the first two disgit? If I do how? Thanks for helping me If date is a string variable then use SUBSTR function eg., Day = SUBSTR(date,1,2); If date is a formatted SAS date value then use DAY function. eg., Day = Day(date); At 04:21 PM 1/22/2009, Tom Smith wrote: >I have the following variable (date) as below: > >Dat...

[Fwd: inline functions and function pointers]
I was wondering if a function pointer pointing to an inline function, will actually expand "inline" when the function pointer is invoked. #include <iostream> #include <vector> using namespace std; const int MAX_FP_SIZE = 10; typedef void (*fp)(int& i); vector<fp> vfptr(0); inline void incr_callback(int& i) { i++; cout << "i is " << i << endl; } inline void decr_callback(int& i) { i--; cout << "i is " << i << endl; } void register_callback(fp fptr) { v...

Use of AMR-Wide Band Codec
I am working with 3GPP AMR WB codec and I am able to successfully compile the encoder and decoder and also run it as mentioned in the document using their voice samples (tst.inp and dtx.inp). I want to implement the codec to encode and decode any general sound (.wav file). How can I do that ? I have tried to convert the .wav filr to .inp which is not happening and then I also tried to use wave file as input to encoder but am not able to implement it. Can I get some help in this regard. _____________________________ Posted through www.DSPRelated.com ...

Using a zip drive (USB) or a CD writer on OpenServer 5.0.7
I have a customer that is planning on upgrading their hardware and either I am not doing something right or the Hardware compatibility page at sco.com is a little hesitant to be forthcoming with this information. We are trying to determine if OpenServer 5.0.7 will support either a Zip Drive, a USB hard drive or a CD-RW/Reader. We currently archive information on their 5.0.5 system using a zip drive (that someone else installed) and as long as they remember to mount and unmount it as they should things work great. They prepare data on the Unix box and then our BBx application moves t...

timer function
Hi All, I wanted to profile my function. I've two choices. 1. using time.h and clock() function. 2. using sys/time.h and gettimeofday() function. Could you help me to know which one is better in precision (advantages/ disadvantages) and under what circumstances one should use which function? My observation : I've used both functions for profiling. clock() doesnt look very precise so I took median of 7 readings and for gettimeofday() I took mean of 5 readings. Both comes almost same. But my knowledge is half and I dont know the answer of my query. Thanks, Nishu Nishu <naresh.a...

script functionality
How to write the script which splits processing based on output from previous filter.ie. IF forward_mail=success THEN color=grey ELSE goto next rule user wrote: > How to write the script which splits processing based on output from > previous filter.ie. > IF forward_mail=success THEN > color=grey > ELSE > goto next rule > If NOT ... Skip Next Rule eg. If not expression headers matches "forward_mail=success" SkipNext "" Always Highlight "14" -- OpenPGP: id=18795161E22D3905; preference=signencrypt; ...

Profiling a mex function
Hello all ! I'm wondering if there is a way to do profiling (like in profile report ) to a mex function, so i can see where it spent the most of the time ? Thank you Nati ...

optimal parameters using FMINCON
Dear All, I am trying to use Fmincon to get optimal 5 parameters, x1-x5. I always get the results like x1=x3=average of (initial value of x1 + inital vaule of x3), x2=x4=average of (initial value of x2 + inital vaule of x4), though I didnot impose constrants in those way. Also tried different initial values and different dataset, still got the similar results. Can anyone help? Thanks.--Ambra In article <1149693187.506833.135720@f6g2000cwb.googlegroups.com>, ambra.chow@gmail.com wrote: > Dear All, I am trying to use Fmincon to get optimal 5 parameters, > x1-x5. I always get the ...

Pointers, pointers, pointers.......
Hi group. Asking again some help to better understand the basic principles of RPL.... In RPLMAN they say: >>>In the most general definition of RPL, I is an object pointer >>>pointing to a composite object that is the top of a stack of >>>composite objects called the runstream. >>>R points to the rest of the runstream stack. What is really meant by *the rest of the runstream* ? Is R pointing to the object right after the one pointed by I? Is R pointing to the rest of the stack *as a whole* (how's it possible?) Anything else I didn't catch? >>...

Function, Dll, and how to call them from any windows program, help Please.
Ref. Windows 2000 service pack 4 Turbo C Version 2.01 Copyright (c) 1987, 1988 Borland International Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland Greeting,this is Roberto, from Italy. I would like to make a dll including two very simple function, like function1 like : function1(5,7), that return "12" function2 like :function2(hello there), that return "Hello There" and be able to call them from any windows program. How can i do that ? Can You help me with a code example for 1) dll code ( including any two simple function ) 2) compile code for the dll...

qualified names in namespace member declarations
There is some previous discussion of this; but, I could not find definitive and unanimous agreement and interpretation of the standard. namespace A { class A::SomeClass { } ; A::SomeClass A::some_func() ; } namespace A { A::SomeClass A::some_func() { return A::SomeClass() ; } } Which of the redundant A:: qualifications above are legal? Is section 8.3 of the standard relevant? What other sections bear on this question? On our system, g++ and the Sun compiler allow the above while the Intel compiler gives the "qualified name not allowed in namespace member declarati...

Is it possible to automatically input title in TOC (using combine package)
Hi all, I am using combine package to collect all aritcles. Instead of using \coltoctitle{Title of article1} \authortochead{name of author1} \import{article1} for putting title and author's name in TOC. Is it possible to automatically input title and author's name in TOC just using \import{article1} because title and author's name are known from article.tex. Thank you in advance. chat ...

Secant Function
I am trying to program a secant function that will help me solve this function: (1+p)/2*(p/(1-p+p^2))^21-0.5 = 0 My code: function x = secant(f,x0,x1,n) ff=inline('f'); xp=x0; fp=f(xp); x=x1; fx=f(x); for i=1:n xn = x-fx*(x-xp)/(fx-fp); xp=x; fp=fx; x=xn; fx=ff(x); end doesn't seem to work however. I have to determine to within 10^-3, the p that will help me solve this solution using initial p's p0=p1 and p1=0.9 and obtain p5=0.84230. I'd really appreciate some help. Thanks in advance. "Ryan " <riley127099@hotmail.com> wrote in mess...

Lost functionality... where have they all gone?
Is there a post or official PTC document that specifies what features where taken out, moved, or reassigned under new functionality etc. From 2001 to Wildfire? I've spent the last two days in frustration trying to find a number of features in Wildfire. For instance, can anyone tell me what happen to all the different Datum Curve types, i.e. Intersection of surfs, Projected, Split, From Curve 2 Projections etc. Guys, people, you are getting needlessly lost! They don't bump into walls and bang into each other in the SolidWorks NG like the Three Stooges. Why should we!?! Do yo...

POINTER EQUALS AN ARRAY
The program below creates a char pointer call charPtr...... i then declare an char array string[10] "Good Luck" When i assign charPtr = string, I expect an error. However, It actually runs and outputs: G Good Luck Can someone explain to me how charPtr = string actually works, but if I create char string = 'x'; wouldn't work. #include<math.h> #include<iostream> using namespace std; void main() { int value; value = 500; char* charPtr; char string[10] = "Good Luck"; charPtr = string; cout<< *charPtr<<endl; cout<<cha...

Anybody using Bull's ARF?
Hi, is anybody in this Forum using Bull's "Application Roll-Over Facility" a product that is compareable to HACMP?? If yes, any bad experiences??? TIA Axel ...

Using the Cache to Change the Width of Memory
On my web site, I had proposed a computer design which started out as a simple big-endian machine, say like a 68000 or a 360, but which added a lot of features, with which I illustrated various architectural concepts. One thing I added was this: Let's say the bus to memory is 64 bits, for example. If I make 16 accesses to memory to fill one cache line, I can make the cache work really fast if I have an internal bus to the cache that is 16 x 64 bits wide. Suppose I made only 9 accesses to memory, and called it a day for filling a particular cache line. Then, I could divide up this parti...

Problems with Oracle functions.
I am trying to convert a number 20070303 into a date format column I have tried a combination like this but I don;t seem to be able to find the right syntax. insert into temp_pa (PRIOR_AUTH_CODE_NUM, eff_date, term_date) select PRIOR_AUTH_CODE_NUM, to_date(to_char(EFFECTIVE_DATE,'99999999'),'YYYYMMDD'), to_date(to_char(TERMINATION_DATE,'99999999'),'YYYYMMDD') from PRIOR_AUTHORIZATIONS; Help!! On 7 Mar 2007 13:28:08 -0800, "Ora" <ed.rohwer@gmail.com> wrote: >I am trying to convert a number 20070303 into a date format column...

pointers as aliases
I would like to use pointers as simple aliases, giving one-letter names to some components of some types, when types and components have meaningful but longer names. Obviously, I don't want to write long mathematical expressions. Of course, the ideal replacement would be the associate construct, but it is not yet implemented by all compilers. So my question is: Is there a significant performance penalty for using pointers as simple aliases? (Two pointers never point to the same component.) Gabor <go@szfki.hu> wrote: > Is there a significant performance penalty fo...