3

I have something like the following structure. It's a container which invokes a callback on all its elements. fct could be a lambda, a functor or a plain function pointer.

Now, in some cases I'd like to optionally configure fct before I call it. For example, fct computes a complicated function on each x. But ContainerX already knows an intermediate result - I would like to tell fct the intermediate result. If fct is a functor, it has a state and it can store the intermediate rsult. If it's a plain function, it can not store the intermediate result and should be called without the pre-configuration.

class ContainerX{ void callback(function<void(X* x)> fct){ // 1. Tell fct the intermediate result, if it is able to be configured // 2. Call fct for all x in the container } } 

There are basically many ways to do this:

  • I could define fct as function<void(X* x, double result)>
  • I could define fct as an abstract class which has the actual function and a preconfiguration function.

But these solution require me to change the signature of callback in a way that I can no longer call it with plain functions as well as with functors.

Is there a way to transparently, optinally configure fct?

11
  • 1
    Let the functions have an optional parameter, that represents the intermediate result. Commented May 20, 2015 at 8:30
  • Sounds interesting, I was not aware of optional parameters in C++. Could you provide a short code snippet how this would look? (Particularly, the signature of fct. Commented May 20, 2015 at 8:36
  • 1
    What do you mean by "I can no longer call it with plain functions as well as with functors."? What would be the problem with having an overload? Commented May 20, 2015 at 8:45
  • I think a good C++ way should be to use virtual methods instead of callback. I solved a lot of problem using C++ virtual methods. Commented May 20, 2015 at 9:17
  • What I meant with optional parameters are e.g. a pointer to the intermediate result, that is null if no intermediate result can be provided or something like boost::optional. Commented May 20, 2015 at 9:39

1 Answer 1

3

I would create an overload of callback does use the result parameter. It would look something like this:

class ContainerX{ void callback(function<void(X* x)> fct){ } void callback(function<void(X* x, double result)>){ } } 

But these solution require me to change the signature of callback in a way that I can no longer call it with plain functions as well as with functors.

There are in essence two different callback functions. One which takes a function using an intermediate value. One that doesn't. Sometime you want different signatures which do roughly the same thing. That's what overloads are for:).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.