The Partridge Family were neither partridges nor a family. Discuss.
-
rekvijem
- Posts: 59
- Joined: December 28th, 2013, 6:39 pm
Post
by rekvijem » February 24th, 2017, 10:43 am
How can i use pointer to member function i mean practical application?
If we need object instance or pointer to object to invoke pointer to member function than
why bother with pointer to member function when we can use only object instance or pointer to invoke function directly?
Code: Select all
struct C
{
int y;
int foo(int x) const { return x+y; }
};
typedef int (C::* FooPtr) (int x);
int C_foobar (int x, C const &c, FooPtr fp)
{
return x + (c.*fp)(x); // we need C instance to call C::foo()
// why not just invoke foo directly like
c.foo(x);
}
This is some example i found online but i can not find any practical application.
-
chili
- Site Admin
- Posts: 3948
- Joined: December 31st, 2011, 4:53 pm
- Location: Japan
-
Contact:
Post
by chili » February 24th, 2017, 11:49 am
I just wrote a mini library to to do dynamic double dispatch that uses pointer to member function at its core.
http://cpp.sh/8ajwm
Chili
-
rekvijem
- Posts: 59
- Joined: December 28th, 2013, 6:39 pm
Post
by rekvijem » March 2nd, 2017, 6:01 pm
Ok, but i still don't understand why not just store pointers to Alpha and/or Beta...?
something like this(i did not write all code couse i am at work and my pc is dead :/ )
Code: Select all
void Dispatcher::Dispatch(DispatchTarget* pSelf, DispatchTarget* pOther)
{
//calculate key, find apropriet pointer and and call handle metod directly using pointer
}
int main()
{
Dispatcher d;
Alpha a(69);
Alpha a2(420);
Beta b;
d.register(a);
d.register(a2);
d.dispatch(a,b)
}
-
chili
- Site Admin
- Posts: 3948
- Joined: December 31st, 2011, 4:53 pm
- Location: Japan
-
Contact:
Post
by chili » March 3rd, 2017, 1:12 am
Because you don't always have the luxury of having differentiated pointers. When you use polymorphism, and you have a container with pointers to Base, from the point of view of the owner of that container, all it sees is a much of pointers to Base, and it cannot tell whether any individual object is actually an Alpha, a Beta, or a what.
My specific use case is Box2D, where a handle to user data can be stored in 'fixtures' in a void*. So you cannot have Alpha*, Beta* etc., and you need some way of discovery and differentiation, so you can dispatch collision events between fixtures properly.
Chili