jmellby@m2.csc.ti.com (John Mellby) (02/07/91)
This question is related to the question several weeks ago (sorry, I lost the
original msg) on passing member functions as parameters.
I have to interface with routines (X Window System routines which I cannot
change) which require a function as input. I would like to simply pass in
a member function on a specific object (like a.print_c() as below). This
function needs to perform actions specific to its object (a).
However, as has been stated before, this isn't possible.
The original solutions involved using a static member function which didn't
have an implicit "this" pointer and thus could be passed as parameters.
In my case I managed to pass not only the static member function, but
a pointer to the specific object as well. Then the static member function
operated on the pointer which had the same effect as if I had been able
to pass in &a.print_c!
What I want to know, is this solution legal in general, or is it only this
compiler (SunOS 4.1, Sparcstation 1+, Cfront 2.1) that makes this legal?
The code which I tested is:
#include <iostream.h>
class test_static;
void apply(test_static *ts, void (*function)(test_static *))
{
function(ts);
}
class test_static {
private:
char *str;
public:
test_static(char *s) { str = s; };
// Because this is static, there is no implicit "this" function
// and this can be passed.
static void print_c(test_static * ts) { cout << ts->str << "\n"; };
};
main()
{
test_static a("test data 1");
test_static b("test info 2");
apply( &a, &(test_static::print_c) );
apply( &b, &test_static::print_c );
}
// The program results are:
test data 1
test info 2
John R. Mellby Texas Instruments
jmellby@skvax1.ti.com P.O.Box 869305, MS 8513
Plano, Texas, 75266
(214)517-5370 <home> (214)575-6774
****************************************************************************
* A friend who used to work at <research lab> related a story
* about a customer support line at <company>. The support person said
* something on the order of "You're not our only customer, you know," to which
* his reply was, "But we're one of the few with tactical nuclear weapons."
* - from USENET
****************************************************************************