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

Link: [33.11] Is it possible to convert a pointer to a function in 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; } 

Questions> Which method, original or updated, is the recommended method? I tested both methods with VS2010 and each prints the correct result.

thanks

Although in the original post I see the following usage:

  void baz() { FredMemFn p = &Fred::f; ← declare a member-function pointer ... } 
+4
source share
4 answers

A function pointer call gives another function pointer. So, just f() , otherwise you are just messing up your code.

Pointers to participants are different animals. They require the use of operators .* Or ->* . This is why you should use std::function (or boost::function ) instead of raw function pointers / memebers.

+6
source

Both are fine:

  p(); (*p)(); 

But the former is preferable because it is more consistent with a 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 using function pointers and a functor object, which became possible only because I used the first syntax.

The moral of the story: strive for a uniform appeal . Write the code in such a way that the syntax of the call is the same, regardless of whether the call object is a function pointer object or a function object.

+6
source

The standard allows you to use all forms, but if you do not want to confuse readers, it is usually best to be explicit: &f take the address of the function and (*p)( x, y ) to call.

+1
source

You can use any form, but for me it looks the most natural:

 p(x, y); 
0
source

Source: https://habr.com/ru/post/1382540/


All Articles