Reputation: 19860
I'm writing a wrapper around an http server in C++. My compiler only support C++03 (gcc 4.1.2) and I can't use boost.
I wanted to implement a generalized callback mechanism to answer the requests, able to register either a function or an object method or a static object method.
A (too) quick glance on <functional>
function objects (C++03, http://www.cplusplus.com/reference/functional/) make me think that it was the answer.
However, it seems that <functional>
function objects are not meant to provide a generalized callback mechanism.
So I wonder : what is the use of <functional>
function objects in C++03 ? What are they meant for ? What true benefits are they supposed to provide over simple functions pointers ? Or is the C++03 version flawed and only the C++11 version is actually useful ?
[edit] For what I had understood at first, it seemed to me that a C++03 function object was just a useless wrapping over a function pointer. I'd rather use the function pointer directly, then. Correcting this wrong analysis is the point of this question !
Upvotes: 3
Views: 899
Reputation: 103741
I don't really understand your question, <functional>
is a header, not a mechanism. The header provides utilities for making function objects conveniently. As a simple example, let's say you wanted to call transform, multiplying the elements of one range by another, and storing the result in a third. You could define a function like this:
double mult(double lhs, double rhs) { return lhs * rhs; };
Then call it like this:
std::transform(lhs.begin(), lhs.end(), rhs.begin(), out.begin(), mult);
Or you could use std::multiplies
, which is already defined for you:
std::transform(lhs.begin(), lhs.end(), rhs.begin(), out.begin(), std::multiplies<double>());
There are many other examples. You just need to be creative. C++11 lambdas have made many of the facilities in <functional>
obsolete, or at least a lot less useful, because you can just define your functions inline with your algorithm calls.
I wanted to implement a generalized callback mechanism to answer the request
The C++03 version of <functional>
does not help you with this. The C++11 version does, with std::function
, adapted from boost::function
.
Upvotes: 2