What is the interest of function objects <function> in C ++ 03?

I am writing a wrapper around a http server in C ++. My compiler only supports C ++ 03 (gcc 4.1.2) and I cannot use boost.

I wanted to implement a generic callback mechanism for responding to requests, capable of registering a function or an object method or a method of static objects.

A (too) quick look at function objects <functional>

(C ++ 03, http://www.cplusplus.com/reference/functional/ ) makes me think this was the answer.

However, it seems that object objects are <functional>

not designed to provide a generic callback mechanism.

So, I wonder: what is the use of function objects <functional>

in C ++ 03? What are they for? What are the true benefits they should provide over simple function pointers? Or is the C ++ 03 version wrong and only the C ++ 11 version is actually useful?

[edit] For what I understood at the beginning, it seemed to me that the C ++ 03 function object was just a useless wrapper over a function pointer. Then I would rather use a function pointer. Correcting this incorrect analysis is the question of this question!

+3


source to share


1 answer


I don't understand your question <functional>

- this is a title, not a mechanism. The header provides utilities for conveniently creating functional objects. As a simple example, let's say you want to invoke a transformation by multiplying the elements of one range by another and storing the result in the third. You can 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 can 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 made many of the objects <functional>

obsolete, or at least much less useful, as you can simply define your functions according to your algorithm calls.

I wanted to implement a generic callback mechanism to respond to a Request

The C ++ 03 version <functional>

won't help you with this. The C ++ 11 version works with std::function

adapted from boost::function

.

+2


source







All Articles