I read over the boost::function function wrappers, and the examples cited in the tutorial section (http://www.boost.org/doc/libs/1_55_0/doc/html/function/tutorial.html). I am trying to understand the use cases of function wrappers, as opposed to just using function pointers. I am not necessarily looking for code samples, but more of cases where functions wrappers are way more appropriate to use than function pointers.
Thank you,
Ahmed.
A function wrapper wraps any callable entity, this includes function pointers as well as function objects and lambda functions.
A function object can be any class that overloads the operator().
Function objects are also the result of calls such as boost::bind or std::bind.
The use of a function wrapper then would be to allow any type of callable object to be used instead of just a function pointer.
Function objects are mostly used to bind values to the object such as maintaining an internal counter to determine how many times the function object was called (tricky to do with just function pointers requiring static variables in the scope of the function pointer), or binding a class instance to a member function for ease of calling later.
By having your class constructor or function take as a parameter a boost::function (or std::function) function wrapper instead of a function pointer, you allow users of your class or function to be able to decide whether they would prefer to pass you a function pointer or a function object or a lambda, and you don't have to care what choice they make.
Related
from Wikipedia - Function object
A typical use of a function object is in writing callback functions. A callback in procedural languages, such as C, may be performed by using function pointers.[2] However it can be difficult or awkward to pass a state into or out of the callback function. This restriction also inhibits more dynamic behavior of the function. A function object solves those problems since the function is really a façade for a full object, carrying its own state.
Why do function pointers make it difficult to pass a state into or out of the callback function and dynamic behavior of the function?
if function do not use function pointer how programs can called function
As far as function pointers in C go, you need to pass the state as an extra parameter. That's in opposition to languages like python, javascript or C++ that have closures. And that means storage duration needs to be considered for that extra structure.
C programmers do make use of function pointers. And you can't write very generic code without using function pointers. We just apply discipline and pass the captured state in a structure, as a function parameter.
I always wondered why there is a stylistic difference between calling a pointer to function vs calling a pointer to a member function in terms of using the de-referencing operator *, i.e.
void(*fptr)()=&f; // pointer to function f()
fptr(); // call f() via pointer to function
Foo foo; // instance of Foo
void (Foo::*fptr)()=&Foo::f; // pointer to member function f()
(foo.*fptr)(); // call foo.f() via pointer to member function
In the first part, you don't use the * operator to call f() via the function pointer, but then one must use it in calling the member function via the pointer, (foo.*fptr)(). Why this difference? Why not just use (foo.fptr)() for consistency? Is there any profound reason or just this is the way C++ was designed?
I'll be quoting stuff from C++ Common Knowledge. The related chapter is titled Pointers to member functions are not pointers. There the author explains why pointers to member functions cannot be implemented as pointer to functions. I'll be using this (the fact that they're different things) as a justification for the different syntax :
When you take the address of a non-static member function, you don't get an address; you get a pointer to member function.
(...)
As with a pointer to data member, we need an object or pointer to an object in order to dereference a pointer to member function. (...) In the case of a pointer to member function, we need the object's address to use as (or to calculate) the value of the this pointer for the function call and possibly for other reasons as well.
Note that there is no such thing as a "virtual" pointer to member function. Virtualness is a property of the member function itself, not the pointer that refers to it.
This is one reason why a pointer to member function cannot be implemented, in general, as a simple pointer to function. The implementation of the pointer to member function must store within itself information as to whether the member function to which it refers is virtual or nonvirtual, information about where to find the appropriate virtual function table pointer, an offset to be added to or subtracted from the function's this pointer and possibly other information. A pointer to member function is commonly implemented as a small structure that contains this information, although many other implementations are also in use.
Dereferencing and calling a pointer to member function usually involves examining the stored information and conditionally executing the appropriate virtual or nonvirtual function calling sequence.
IMHO considering these differences one can justify the syntax difference, although historic design choices could have played their role.
If we simply use foo.fptr, it is the same as how we call a member function, making the compiler complex. Actually, fptr is not a member function of foo. Thus *fptr shows the difference. Maybe the compile can make that happen ,and I think that's how C++ was designed now.
I am newbie for the concept but as I search the difference and the good of the functors is that they are able to store values inside and initialize these values from the construction but normal functions also work in same fashion except they take the all arguments as whole at the function call. Most probably I am wrong in some way but where is the trick and the benefit of functors in relation to normal functions
The core difference is that a functor defines a type not a function. Even stateless functors (without any attached data) can take advantage of this. For example consider the use of std::less inside a sorting algorithm:
template <typename Iterator, typename Comparator>
sort(Iterator begin, Iterator end, Comparator c) {
...
if (c(*begin,*end)) { ...
...
}
Called as sort(v.begin(), v.end(), std::less<int>());. When the function is called, an instance of std::less<int> is created and passed to the template. Because it is stateless, the cost of passing the function is almost nothing. Inside the function, the call c(a,b) is determined to be a call to c.operator()(a,b), and the compiler knows the type. It can efficiently inline the call (which in this case is simple enough) and substitute it by a single compare instruction.
On the other hand, the equivalent C function qsort takes a function pointer (you cannot pass functions by value). Inside qsort, the compiler does not know what the function called is, and it cannot inline it, so it must perform a function call for each comparison.
Functors serve both to add extra information that can later be used at the place of call (this is impossible with a plain function), and to pass extra information like provide information like what needs to be called (the same behavior can be obtained, but with a hit on performance) or other attached information (the type can have nested types/typedefs, information for traits inspection...)
Normal functions, free-standing or member, only have their arguments which will be passed when the function is called. So there is no way to pass extra data to the function.
This is different with a functor. A functor is an instance of an object, and as such can indeed store data passed to its constructor (which you use when passing the functor).
With C++11 things are muddled up a bit, as lambdas can also "store" (not technically correct word) values by using captures. Or by using std::bind which allows you to bind values as arguments when the callable object is actually called.
I would like to call a function g (from a 3rd party library) that takes as input a pointer to a function f. This function pointer is such that f itself takes some arguments.
As my function f depends on data and I cannot pass (a reference to) this data as a parameter to the function f because I need to implement f using the signature that is used in the function pointer, I would like to do one of two things:
implement f as a (non-static) member function of a class
implement a helper function fHelper that takes additional arguments and then construct a function pointer (but not a function object) that has the signature of the function pointer used in g and calls fHelper with the additional arguments bound to specific values.
A third solution that is neither thread-safe nor acceptable from the perpective of design would be to use a global variable.
I have looked at boost:bind and std::mem_fun but do not understand if these concepts work in this setting. I would very much appreciate an instructive answer and possibly some background on how this case is usually handled.
For example, considering the C#
Unlike function pointers in C or C++, delegates are object-oriented,
type-safe, and secure.
source:
http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx
Now talking about the C++ only, what is the real difference and what is missing from an OO prospective?
Also from another source
Most C++ programmers have never used member function pointers, and
with good reason. They have their own bizarre syntax (the ->* and .*
operators, for example), it's hard to find accurate information about
them, and most of the things you can do with them could be done better
in some other way. This is a bit scandalous: it's actually easier for
a compiler writer to implement proper delegates than it is to
implement member function pointers!
source:
http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible
I find that many programs in C++ uses the ->* syntax, i don't find that this is bizarre or strange; I don't get the point about this potential about the delegates and the attack to the pointers.
The difference between a member pointer and a true closure is that a closure contains the function and the associated state. The two are inseparable.
A member pointer is just the function. In order to call a member pointer, you must provide the state.
It's the difference between a function pointer and a functor. The function object holds the function to be called (as an overload of operator()), but it can also have members. Those members can be private, thus providing encapsulation. The function object is an object by C++ rules, so it has an explicit lifetime. It is constructed and destructed according to C++ rules.
A function pointer has no lifetime; it always exists (unless it's NULL). It has no state to encapsulate.
Therefore, it's not a closure because it can't close over anything.
That's why C++11 lambdas are implemented as explicit objects. That way, they can close over things. They have encapsulated state.
I think people find it difficult to write them, but they behave like ordinary pointers, if they are NULL then its wrong to execute them. If they are written and used properly then there is nothing wrong with them. I never really had problems with,maybe besides forgetting proper syntax.
In c++11, you can use std::function<> class which is a wrapper for function pointer. You can use it for functions, member functions, functions objects and lambdas.
for example:
void foo(int x);
std::function<void(int)> f=foo;
f(1);
or easier (works in VS2010):
void foo(int x);
std::function<decltype(foo)> f=foo;
f(1);
ref: http://en.cppreference.com/w/cpp/utility/functional/function
Member function pointers are not member functions. Function pointers in C/C++ are dangerous in the sense that they could point to deallocated memory or be set to NULL at any time. Generally they are avoided, though not always with things like boost::bind or swapping print functions.
Thus in general they aren't any more dangerous than standard pointers. However, you can oftentimes avoid using function pointers by just calling an object's member method or a static function somewhere else. It compiles to using function pointers on the inside, but you have better guarantees about the existence of that function when it gets called.