473,769 Members | 2,100 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
37 5019
Ben
Siemel,

Although some implementations may use the same size, it is not stated
in the standard that they will be of the same size.
As far as I know, VC uses different sizes for classes with and without
virtual functions and multi-inheritance.
"Siemel Naran" <Si*********@RE MOVE.att.net> wrote in message news:<1C******* ************@bg tnsc04-news.ops.worldn et.att.net>...
"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 #11
On 11 Jun 2004 04:14:22 -0700, Mi************* @logicacmg.com (Michiel
Salters) wrote:

[snip]
class InternalHelperC lass;
typedef (void InternalHelperC lass::* PTMF)();


Doesn't InternalHelperC lass need to be a complete type here?

[snip]
--
Bob Hairgrove
No**********@Ho me.com
Jul 22 '05 #12
Ben
Ok. I think I misunderstood you.

So you are saying that it is the upcast from (C::*)() to (B::*)() that
kills the implementation of a function pointer.

Yes. That does explain the problem. Although I'd rather call it
"downcast" because it is not type-safe.

Well. Thanks a lot, Andrey. You clarified my question. Although I
really hope the PTM upcast for Multi-inheritance and virtual functions
(where subclass has virtual and super does not) had never been
approved. :-)
Jul 22 '05 #13
Ben
Andrey,
yes, yes. it's me again. And yes, I do understand the function pointer
does not work as an implementation for the current PTM spec and it is
the upcast that kills it.
However, I found my original question still not answered.
"why PTM in the first place"?
What if, there's not an animal called "pointer to member function" at
all? What if MyClass::foo only evaluates to a function pointer of type
"void(*)(MyClas s*)"?

In that way, B::bar is of type "void(*)(B* )" and C::baz is of type
"void(*)(C* )".

Nothing's special here, nothing needs special spec. Programmer already
know not to cast "void(*)(C* )" to "void(*)(B* )" for case of "C:public
A, public B".
Isn't that simpler? We will be still living in the familiar farm with
sheeps and cows like "function pointer". No unicorn from the forest
such as PTM to disturb the peace.
Jul 22 '05 #14
Ben wrote:
...
However, I found my original question still not answered.

"why PTM in the first place"?

What if, there's not an animal called "pointer to member function" at
all? What if MyClass::foo only evaluates to a function pointer of type
"void(*)(MyClas s*)"?

In that way, B::bar is of type "void(*)(B* )" and C::baz is of type
"void(*)(C* )".

Nothing's special here, nothing needs special spec. Programmer already
know not to cast "void(*)(C* )" to "void(*)(B* )" for case of "C:public
A, public B".

Isn't that simpler? We will be still living in the familiar farm with
sheeps and cows like "function pointer". No unicorn from the forest
such as PTM to disturb the peace.


Hmm... As I said in my previous message, the extra functionality (the
permission to call 'void C::baz()' through a 'void (B::*)()') was added
to PMFs in the second draft of C++ specification. The reason it was
added is that someone in the standard committee thought that this
behavior is needed and others agreed.

You are saying that "programmer already know not to cast 'void(*)(C*)'
to 'void(*)(B*)' for case of 'C:public A, public B'" I don't exactly
understand what you are trying to say. Casting 'void (C::*)()' to 'void
(B::*)()' is perfectly legal in C++ and required to work correctly (as
was described before). I.e. programmer already knows that he _can_ do it
and that it will work. The approach that you propose kills that
functionality. In that respect your approach is not equivalent to what
we have in C++ today.

So, the answer to your question is that we need PTM as a beast of
completely different nature (from ordinary function pointer) because we
need to be able to implement some PTM-related functionality, which is
not implementable with ordinary function pointers.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #15
Ben wrote:
...
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?
Actually, applying 'static_cast' to a PFM is a form of "pointer
arithmetic" in some general meaning of the word. In a traditional
implementation 'static_cast' applied to PFM will change the PFM (or,
more precisely, some portion of PFM's internal representation) . That's
why we need PFM as runtime variables.
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 most cases. But not in general case.
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.


This solution will not do. You see, in my original example function
'foo' was the actual algorithm that we were trying to implement. You
should not split 'foo' into several functions because that defeats the
purpose of using function pointers. Moreover, the only reason you were
able to do it so easily is because in my original example function 'foo'
was very short an simple (it contained only one PMF call). But what
would you do if 'foo' looked as follows

void foo_3(B* pb, void (B::*pbm[3])()) {
(pb->*pbm[0])();
(pb->*pbm[1])();
(pb->*pbm[2])();
}

In order to split this function, you'll have to generate relatively
large number of variants of 'foo_3' (all possible combinations). But it
is still doable. But look at this

void foo_n(B* pb, void (B::*pbm[])(), unsigned n) {
for (unsigned i = 0; i < n; ++i)
(pb->*pbm[i])();
}

Not splitting 'foo_n' into all possible variants is not an option for
obvious reasons. What are going to do in this last case?

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #16
Ben
> 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.


That actually sounds a good news to me, if true.

Actually that was the first attempt I was trying to make: use a void
PTM and cast it back to what it was.
However, I just could not find a statement saying that this is safe.

From what I read in this group and other articles on the internet, it
is only guaranteed that you can upcast and downcast between super
classes and subclasses.

Could you point me to the source stating that cross-casting between
any two PTM is safe and portable?
Jul 22 '05 #17
Ben
Let me try to summarize a little bit.

1. function pointer could have been a more efficient and simpler PTM.
2. function pointer won't be able to support certain castings when
Multi Inheritance or virtual functions are involved.

So the decision was made in favor of the "castings in Multi
inheritance" and in sacrifice of simplicity and efficiency.

In the current design of PTM, people like me, who want to get a
fixed-size PTM or want to get a function pointer compatible PTM
suffer. We have to use functor objects, wrapper functions or run-time
cost to get around the problems.
Whereas if the decision had been made differently, people who want a
fixed size PTM or a function pointer compatible PTM would be happy,
while people who try to do casting with "multi-inheritance" present
will suffer. They would have to write functor objects, wrapper
functions or other techniques to get around.
The question is trade-off. If someone has to pay the price, who should
be the victim?
From where I'm standing, certainly I don't want to be among the people
who suffer. I'm just trying to do vanilla code, why force me to do all
that hassel?

Actually I would wonder "why people want castings among PTM and
Multi-inheritance at the same time?"
And "Even if they do want it, what's the big deal of writing the
functor objects as we are currently forced to do? They choose
Multi-inheritance, they choose casting, which means they choose the
complexity in the first place anyway."
Best Regards,

Ben. Y.
Jul 22 '05 #18
Ben wrote:
...
Could you point me to the source stating that cross-casting between
any two PTM is safe and portable?
...


You can read about it in 5.2.10/9. But note that that's not
"cross-casting between any two PTM". That would be neither safe nor
portable. Safe and portable is the round-trip 'renterpret_cas t'.
"Round-trip" is this case means that you may cast one PMF type to
another PMF type, but you have to cast it back to the original PMF type
before attempting to use it as PMF.

(Wasn't it already mentioned in this discussion before? OR am I thinking
about some other discussion?)

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #19
Ben
Yes, "Casting 'void (C::*)()' to 'void (B::*)()' is perfectly legal in
C++".

I agree with that.

What I was talking about was casting 'void (*)(C*)' to 'void (*)(B*)'.

As long as function pointer is still a valid citizen in the language,
casting between two function pointers is also valid citizen in the
language.

And we programmers know it is not safe to cast from 'void (*)(C*)' to
'void (*)(B*)' in case of "C::A,B", don't we?

Even with PTM today, it is still possible that I write this code:
void f1(B*){...}
void f2(C*){...}
void(*p1)(B*) = (void(*)(B*))f2 ;

The existence of PTM does not prevent us from doing this. What saves
us from making this mistake is knowing that "this is not safe" and
contientiously staying away from it.
So, if we had no PTM at all, if PTM was just an alias of function
pointers, would it surprise anybody that we cannot do this cast? I
think not.


In my other post I concluded my understanding of this entire issue. It
is all about trade-off. Somebody in the committee thought it is more
important to have a handy way to do the cast, while somebody like me
is complaining we paid too much for this convenience that is rarely
needed.
Jul 22 '05 #20

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

Similar topics

9
7740
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
9376
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
8829
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
3653
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
4402
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
9422
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
10208
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
9987
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,...
1
7404
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
6662
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();...
0
5444
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3952
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
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2812
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.