Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we use p(..) or (*p)(..) when p is a function pointer?

Tags:

c++

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
   ...
 }
like image 627
q0987 Avatar asked Dec 13 '22 07:12

q0987


2 Answers

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.

like image 138
Cat Plus Plus Avatar answered Jan 02 '23 04:01

Cat Plus Plus


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.

like image 29
Nawaz Avatar answered Jan 02 '23 04:01

Nawaz