473,756 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why pointer to member function?

Ben
Hi, there.

Recently I was working on a problem where we want to save generic
closures in a data structure (a vector). The closure should work for
any data type and any method with pre-defined signature.

When developing this lib, I figured that the
pointer-to-member-function, although seemingly an attractive solution,
does not work well for us.

The size and the memory model of a generic PTMF is not guaranteed,
therefore, cannot be saved in a heterogeneous container.

My solution turned out to be a C callback function pointer.

That is, instead of using a "int T::(*f)()", use a "int (*f)(T*)".

Although a wrapper function that does the forward call is needed, it
solved our problem.
For instance:

instead of calling

add_closure(&ob j, &MyClass::f) ;

I do
int mywrapper(*MyCl ass pobj){
return pobj->f();
}
add_closure(&ob j, &mywrapper);

Here, 2 assumptions were made:
1. all pointers have the same size as void*
2. all function pointers have the same size.

Then, the annoying wrapper function makes me think:

Why PTMF in the first place?
What if the language generates the wrapper function implicitly and
makes MyClass::f a regular function pointer of type int (*)
(MyClass*)?

At least it can make my life much easier. And I wonder whose life will
it make harder?

Dislike the ptmf(pobj) syntax? Still like the pobj->ptmf()syntax ? No
problem, the language can still do that, as long as it guarantees the
binary memory model of a PTMF is a function pointer. I don't mind
doing a reinterpret_cas t here.

Well, just when I'm about to finish, my gut's feeling starts yelling
hard: "No! It can't be right. This must have been thought over 1000
times! You must be missing something here."

"All right, sir. so what am I missing here?"
Jul 22 '05 #1
37 5014
"Ben" <be****@asc.aon .com> wrote in message
news:ff******** *************** **@posting.goog le.com...
Hi,
Recently I was working on a problem where we want to save generic
closures in a data structure (a vector). The closure should work for
any data type and any method with pre-defined signature.

[....]

I recommend you take a look at boost::function :
http://www.boost.org/doc/html/function.html

An equivalent class is expected to be included in the next
revision of the C++ standard. See:
http://anubis.dkuug.dk/jtc1/sc22/wg2...2003/n1540.pdf
Cheers,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- e-mail contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 22 '05 #2

"Ben" <be****@asc.aon .com> wrote in message
news:ff******** *************** **@posting.goog le.com...
Hi, there.

Recently I was working on a problem where we want to save generic
closures in a data structure (a vector). The closure should work for
any data type and any method with pre-defined signature.

When developing this lib, I figured that the
pointer-to-member-function, although seemingly an attractive solution,
does not work well for us.

The size and the memory model of a generic PTMF is not guaranteed,
therefore, cannot be saved in a heterogeneous container.

My solution turned out to be a C callback function pointer.

That is, instead of using a "int T::(*f)()", use a "int (*f)(T*)".

Although a wrapper function that does the forward call is needed, it
solved our problem.
Have you seen http://www.boost.org/libs/libraries....ction-objects?
Which does all of the above and more. And boost::function at least is in the
upcoming C++ TR1.

typedef boost::function < int() > tFnc;
typedef std::vector< tFnc > tFncs;

tFncs.push_back ( boost::bind( &MyClass::f, pobj ) );

int somevalue = (tFncs.front()) (); // = pobj->f();

Or use boost::signals:

boost::signal< int() > mysig;

mysig.connect( boost::bind( &MyClass::f, pobj1 ) );
mysig.connect( boost::bind( &MyClass::f, pobj2 ) );

mysig(); // executes both of the above

You can even specify combiners that do something with the return values from
each f() call.

Jeff F
For instance:

instead of calling

add_closure(&ob j, &MyClass::f) ;

I do
int mywrapper(*MyCl ass pobj){
return pobj->f();
}
add_closure(&ob j, &mywrapper);

Here, 2 assumptions were made:
1. all pointers have the same size as void*
2. all function pointers have the same size.

Then, the annoying wrapper function makes me think:

Why PTMF in the first place?
What if the language generates the wrapper function implicitly and
makes MyClass::f a regular function pointer of type int (*)
(MyClass*)?

At least it can make my life much easier. And I wonder whose life will
it make harder?

Dislike the ptmf(pobj) syntax? Still like the pobj->ptmf()syntax ? No
problem, the language can still do that, as long as it guarantees the
binary memory model of a PTMF is a function pointer. I don't mind
doing a reinterpret_cas t here.

Well, just when I'm about to finish, my gut's feeling starts yelling
hard: "No! It can't be right. This must have been thought over 1000
times! You must be missing something here."

"All right, sir. so what am I missing here?"

Jul 22 '05 #3
Ben wrote:
...
What if the language generates the wrapper function implicitly and
makes MyClass::f a regular function pointer of type int (*)
(MyClass*)?

At least it can make my life much easier. And I wonder whose life will
it make harder?

Dislike the ptmf(pobj) syntax? Still like the pobj->ptmf()syntax ? No
problem, the language can still do that, as long as it guarantees the
binary memory model of a PTMF is a function pointer. I don't mind
doing a reinterpret_cas t here.

Well, just when I'm about to finish, my gut's feeling starts yelling
hard: "No! It can't be right. This must have been thought over 1000
times! You must be missing something here."
...


You are missing the fact that in general case the situation with member
function calls is much more complex than in case of ordinary function
calls. Consider the following example

struct A { int a; };

struct B {
int b;
void bar() { b = 1; }
};

struct C : A, B {
int c;
void baz() { c = 2; }
};

void foo(B* pb, void (B::*pbm)()) {
(pb->*pbm)();
}

int main()
{
B b;
foo(&b, &B::bar);

C c;
foo(&c, static_cast<voi d (B::*)()>(&C::b az));
}

Both calls to 'foo' and consequent indirect calls to member functions
'bar' and 'baz' are valid in C++. Note though, that in order to perform
the member call inside 'foo' correctly the compiler shall be able to
produce the correct 'this' pointer to pass to the member function being
called. In general case, the compiled code will have to perform
adjustment of object pointer value before the actual call. The nature of
the correction depends on the memory layout of the class (which is
implementation-dependent). In the above example there's no direct need
for any correction inside the first call to 'foo', but it might be
necessary to adjust 'pb's value inside the second call to 'foo' (since
we need a pointer to the entire 'C' object, not to a 'B' subobject). In
general case, the information required for this adjustment is generated
by 'static_cast' and stored in the pointer itself, along with the
address of the member function's entry point. For this reason, member
function pointers are usually bigger than ordinary function pointers and
there's no way to replace the former with the latter (unless you are
willing to increase the size of the latter, which in some applications
will result in waste of memory).

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #4
Ben
Jeff,
Thanks for refering me to this nice article.

boost function does look clean and powerful. I have no doubt about the
usefulness of this lib.

However, it does not answer my question.

Let me rephrase my question and reasoning:

I want a simple,clean,ch eap way that can save the member function
closure into a vector, which implies that the element size has to be
fixed for any type of closure.

And because of the following 2 reasons, it is not possible to save a
ptm INLINE in a vector:

1. pointers to member function don't have the same size and the
maximum size cannot be even predictable.

2. don't want to save a pointer to a pointer to a member function
because a pointer to a member function is normally a constant.

the boost lib does prove that I'm not wrong on this. It uses "new" to
allocate space for the closure in heap! That gets around the problem.

Although the interface of boost looks very pleasant and all the memory
management are hidden under the hood, the fact that "new" has to be
used for what should have been a vanilla thing makes me feel sad.

In my specific case, I don't need all the rich features such as
bindXXX, all I need is to pass a member function for a hook callback.
And calling a "new" for every closure where I don't have to is a bit
of a overkill to me. I don't quite like to pay that price.

My final question about "why pointer to member function at all?" came
from this thought:
What if, let's just say "what if", there's no "PTM" at all, MyClass::f
simply yields a function pointer of type "int (*)(MyClass*)"?

Isn't that simpler, faster and has better compatibility with the
already-existing function pointer? And, more importantly, does it
work?
The "D&E" book justifies PTM as:

"... This only worked with a liberal sprinkling of explicit casts that
never ought to have worked in the first place. It also relied on the
assumption that a member function is passed its object pointer as the
first argument in the way Cfront implements it"

My arguments are:
1. It can be type safe to make T::*f a function pointer of
"int(*)(T*) ", if the language wants to do so. Since I can create the
wrapper function manually, there's no reason the compiler cannot
implicitly create it.

2. Making "MyClass::f " a pointer of type "int(*)(T*) " does NOT rely on
an implementation where the "this pointer" is passed as the first
argument.

Evidence? Well, look at the wrapper function again.

Whatever the implementation is, you can pass it as the first param,
the second, or weirdly enough - from a global variable, the function
pointer "MyClass::f " simply points to a function from which you can
eventually invoke the real underlying member function.

There's no promise made that this function must have the same address
of the real "member function". It may be the same address of the real
function, may be an address of a proxy function, all up to the
implementation.

3. Even if we do want a PTM where we can enjoy the favorable syntax
"p->ptm(...)", the implementation of PTM can still be such function
pointer.
Jul 22 '05 #5
Ben wrote:
...
I want a simple,clean,ch eap way that can save the member function
closure into a vector, which implies that the element size has to be
fixed for any type of closure.
...
Unfortunately in ?++ there's no portable way to implement the kind of
closure that would produce an ordinary function pointer (if that's what
you are looking for), although I've seen many platform-specific solutions.

If you are looking for a portable solution, there's no other choice but
to store both the object reference and the member function pointer. You
can do it yourself (as you described in your original message) or you
can a solution provided by some library, you'll still get a _functional_
_object_ as the result of the closure, never a function pointer. In one
way or another you'll have to manage memory occupied by that object.
And because of the following 2 reasons, it is not possible to save a
ptm INLINE in a vector:

1. pointers to member function don't have the same size and the
maximum size cannot be even predictable.
Actually in practical implementations they normally do have the same
size. It is just not the same as ordinary function pointers.
...
My final question about "why pointer to member function at all?" came
from this thought:
What if, let's just say "what if", there's no "PTM" at all, MyClass::f
simply yields a function pointer of type "int (*)(MyClass*)"?

Isn't that simpler, faster and has better compatibility with the
already-existing function pointer? And, more importantly, does it
work?
It doesn't work in general case. I explained the problem in my previous
message.

The "D&E" book justifies PTM as:

"... This only worked with a liberal sprinkling of explicit casts that
never ought to have worked in the first place. It also relied on the
assumption that a member function is passed its object pointer as the
first argument in the way Cfront implements it"

My arguments are:
1. It can be type safe to make T::*f a function pointer of
"int(*)(T*) ", if the language wants to do so. Since I can create the
wrapper function manually, there's no reason the compiler cannot
implicitly create it.

2. Making "MyClass::f " a pointer of type "int(*)(T*) " does NOT rely on
an implementation where the "this pointer" is passed as the first
argument.

Evidence? Well, look at the wrapper function again.

Whatever the implementation is, you can pass it as the first param,
the second, or weirdly enough - from a global variable, the function
pointer "MyClass::f " simply points to a function from which you can
eventually invoke the real underlying member function.

There's no promise made that this function must have the same address
of the real "member function". It may be the same address of the real
function, may be an address of a proxy function, all up to the
implementation.


Your wrapper function has significantly narrower functionality than PMFs
in the language. It always calls a function with pre-defined name. Take
a look at my other message. The functionality presented by an example
there cannot be implemented by such wrapper function.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #6
"Ben" <be****@asc.aon .com> wrote in message
The size and the memory model of a generic PTMF is not guaranteed,
therefore, cannot be saved in a heterogeneous container.


It is garaunteed, I think. On my platform sizeof(member function pointer) =
8 bytes, whereas sizeof(non-member function pointer) = 4 bytes.
Jul 22 '05 #7
Andrey Tarasevich wrote:
...
Your wrapper function has significantly narrower functionality than PMFs
in the language. It always calls a function with pre-defined name.
...


I admit that saying that "It always calls a function with pre-defined
name" is not very precise description of the problem with your
wrapper-based approach. Let me make another, more organized attempt at
the explanation.

There is an important change that took place between the first and the
second version on draft C++ specification (and made it into the final
standard) when it comes to PMFs. If you care to see it for yourself, I
suggest you compare 5.2.9/9 ('Static cast') in these versions of the
document and also note the addition of 5.5/4 ('Pointer to member
operators') in the latter. Essentially this change boils down to one
thing: new version allows upcasts for member pointers (including PMFs)
with 'static_cast'. It was illegal in the first draft. This seemingly
innocent change has very serious consequences. Using PMFs, it became
possible to call member function of a derived class with an object
expression of base class type (the example in my first message
demonstrates such a call). The obvious problem here is that in order to
perform such a call the program has to be able to obtain the correct
'this' pointer for the derived class' member function. All it has at the
moment of the call is two pointers: a pointer to some base class
subobject and a PMF.

In a single inheritance context the problem has trivial solution. Simply
organize class memory layouts in such a way that all base class
subobjects start at the same address as the entire object. In this case
a pointer to a base class subobject can be immediately used as a pointer
to the derived object. No adjustments required.

But once we get into the realm of multiple inheritance, things get more
complicated. It is no longer possible to keep all base class subobjects
aligned at the origin of the entire object. Some base class subobjects
will have to reside at certain offset from the origin. This immediately
means that in order to perform the correct member function invocation
through a PMF the code might be required to "convert" base class pointer
to derived class pointer by adding certain non-zero offset to the
former. Note that the concrete derived type is not known at compile
time, which means that this functionality will require certain amount of
additional run-time information in order to be able to calculate the
offset in question. This additional information (most often - the offset
itself) is usually stored inside the PMF. In a traditional
implementation a PMF contains two pieces of information: the target
address (function entry point) and the offset (adjustment value for
object pointer). That's what turns PMFs into beast of completely
different nature from ordinary function pointers.

Now, your wrapper-based approach is not capable of supporting this
particular functionality of PMFs (calling derived class' member function
with an object expression of base class type). Your approach is more or
less equivalent to PMF functionality described in the first draft of C++
specification. Moreover, it is safe to say that if that first version
made it into the final standard, we would be working today with PMFs
that have the same size as ordinary function pointers and your wrappers
would not be necessary (at least for your purposes). But that's not the
case.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #8
be****@asc.aon. com (Ben) wrote in message news:<ff******* *************** ***@posting.goo gle.com>...
Hi, there.

Recently I was working on a problem where we want to save generic
closures in a data structure (a vector). The closure should work for
any data type and any method with pre-defined signature.

When developing this lib, I figured that the
pointer-to-member-function, although seemingly an attractive solution,
does not work well for us.

The size and the memory model of a generic PTMF is not guaranteed,
therefore, cannot be saved in a heterogeneous container.


Wrong. The basic assumptions are right, but the logic is flawed. Any
particular PTMF can be saved. Other PTMFs can be cast to that single
type, and be cast back where used.

E.g.
class InternalHelperC lass;
typedef (void InternalHelperC lass::* PTMF)();

PTMF genPtr = reinterpret_cas t<PTMF>( &MyClass::MyMet hod );

PTMF may have a different implementation than &MyClass::MyMet hod,
which means that genPtr can't be used directly. However, if it
is casted to the correct MyClass::* type, the resulting value
cab be used. At the point of call, you have all arguments for
MyMethod, so logiaclly you do know the type you must cast to.

(rest snipped, followed from flawed logic)

Regards,
Michiel Salters
Jul 22 '05 #9
Ben
Andrey,
Thanks for the attention and the detailed explanation.

Your example clarifies the difficulty to represent a PTM at runtime,
which I totally agree.

However, do we really need a PTM at runtime? Is it necessary? We don't
have any pointer arithmetic for PTM that makes a PTM variable really
meaningful, do we?

In most cases, where people do "&T::foo", the PTM value is known at
compile time and can be safely transformed to a function pointer.

In my wrapper function approach, I don't attempt to pass the PTM to
the function at all.

Here's my solution to the example:

void foo_bar(B* pb) {
pb->bar();
}
void foo_baz(C* pc){
pc->baz();
}
int main()
{
B b;
foo_bar(&b); //correspond to B::bar
C c;
foo_baz(&c); //correspond to C::baz
}

What I'm hoping is that the compiler can implicitly generate foo_bar
and foo_baz for me. That saves a lot of keystrokes.
As a bonus,such compiler generated wrapper functions should take
advantage of the tail-call and makes minimal overhead for extra
function-call and no overhead or side-effect for extra parameter
passing and return value copying. In other words, RVO is guaranteed
here.
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
7738
by: David Hill | last post by:
Hello - I am using a library that takes a function pointer as an argument. Is the code below not possible? int library_func(void (*func)(int, short, void *)); I am trying to do this... class Test {
5
9374
by: Newsgroup - Ann | last post by:
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);
7
3038
by: jon wayne | last post by:
Hi I'm a little confused here about the lifetime of a static pointer to member function, Say, I declare,define & initialize a static ptr to mem function in the header file of a class(the class is a helper Singleton class, and is created & deleted as and when required) - Where does the static pointer point to when every single instance of the class is deleted. I presume it'll be dangling pointer- as the code seg to which it's
6
8828
by: keepyourstupidspam | last post by:
Hi, I want to pass a function pointer that is a class member. This is the fn I want to pass the function pointer into: int Scheduler::Add(const unsigned long timeout, void* pFunction, void* pParam)
7
3813
by: WaterWalk | last post by:
Hello. I thought I understood member function pointers, but in fact I don't. Consider the following example: class Base { public: virtual ~Base() {} }; class Derived : public Base {
5
4663
by: Tim Frink | last post by:
Hi, I'm experimenting with function pointers and found two questions. Let's assume this code: 1 #include <iostream> 2 class A; 3 4 //////////////////////////////////////////// 5 class B
5
3651
by: Immortal Nephi | last post by:
I would like to design an object using class. How can this class contain 10 member functions. Put 10 member functions into member function pointer array. One member function uses switch to call 10 member functions. Can switch be replaced to member function pointer array? Please provide me an example of source code to show smart pointer inside class. Thanks....
4
4401
by: Immortal_Nephi | last post by:
I had a lot of research to see how function pointer works. Sometimes, programmers choose switch keyword and function in each case block can be called. Sometimes, they choose ordinary function pointer array instead of switch. They believe that ordinary function pointer is much faster than switch. Think of one variable called selectFunction. selectFunction variable can be the range of 0 through 1,000 or more. Load selectFunction...
7
3829
by: ghulands | last post by:
I am having trouble implementing some function pointer stuff in c++ An object can register itself for many events void addEventListener(CFObject *target, CFEventHandler callback, uint8_t event); so I declared a function pointer like typedef void (CFObject::*CFEventHandler)(CFEvent *theEvent);
0
9255
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9819
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7226
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6514
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3780
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.