Reference: [33.11] Can I convert a pointer-to-function to a void*?
#include "stdafx.h"
#include <iostream>
int f(char x, int y) { return x; }
int g(char x, int y) { return y; }
typedef int(*FunctPtr)(char,int);
int callit(FunctPtr p, char x, int y) // original
{
return p(x, y);
}
int callitB(FunctPtr p, char x, int y) // updated
{
return (*p)(x, y);
}
int _tmain(int argc, _TCHAR* argv[])
{
FunctPtr p = g; // original
std::cout << p('c', 'a') << std::endl;
FunctPtr pB = &g; // updated
std::cout << (*pB)('c', 'a') << std::endl;
return 0;
}
Question> Which way, the original or updated, is the recommended method? I have tested both methods with VS2010 and each prints the correct result.
Thank you
Although I do see the following usage in the original post:
void baz()
{
FredMemFn p = &Fred::f; ← declare a member-function pointer
...
}
Dereferencing a function pointer yields another function pointer. So, just f()
, otherwise you're only obfuscating your code.
Pointers to members are different beasts altogether. They require usage of .*
or ->*
operators. That's also why you should use std::function
(or boost::function
) instead of raw pointers to functions/memebers.
Both are okay:
p();
(*p)();
But the first one is preferable, because it is more consistent with functor object. For example, you can write a function template as:
template<typename Functor>
void f(Functor fun)
{
fun(); //uniform invocation - it doesn't matter what it is.
}
Now this can be called with function pointers, and functor object, both, which has been made possible only because I have used the first syntax.
The moral of story is : strive for uniform invocation. Write code in such a way that invocation syntax should be same irrespective of whether the invocation-entity is a function pointer or function object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With