1

I have a base function

int base(const int i, const double &x)

In this function, I consider i to be a "parameter" (which can take predefined values from 0 to N-1), while x I consider to be the actual "argument" (which can take any arbitrary value).

What I need is to create an array of function pointers int (*pointers[N])(const double &x). Each member of the array corresponds to a different value for the parameter i and thus each call pointers[n](x) should be equivalent to a call base(n, x).

Is there a way to achieve this functionality?

I have been trying to educate myself about functors (is this a way to go?) and recently also looked into std::bind but my understanding is that it only works with C++11 (which I currently cannot use).

Any advice or code snippet would be really helpful. Thanks!

1 Answer 1

1

You can use non-capturing lambdas for that:

typedef int (*fp)(double);

fp p1 = [](double x) -> int { return base(1, x); };
fp p2 = [](double x) -> int { return base(2, x); };
fp p3 = [](double x) -> int { return base(3, x); };

This doesn't work for capturing lambdas, and so you can't generate those programatically. There's essentially no difference between this and spelling out one function for each value in C:

int f1(double x) { return base(1, x); }
fp p = f1;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer!....the problem is the following: The number of different parameter values is large and, more importantly, not known at compile-time. Thus, I cannot just casually write "p1", "p2", "p3", "f1", etc....I need to be able to do commands in a loop over i....
@Chrys: Unfortunately, functions in C++ are not real first-class objects, and you cannot create functions dynamically. If you could use function-like objects, it would be trivial, but not with raw function pointers. They just don't carry enough state.
I need to use raw pointers in order to interface with legacy code originally written in Fortran, which I have been calling through C (which has been a mess of its own)....I have been thinking along the lines of using a functor class, the call operator of which will be linked to each different function, and a different object of which functor will be created in the loop over the parameter values (however, I am not too proficient to know how to do this exactly)
@Chrys: You can't do that. A raw C function has no state, and you cannot make something that has more state than none at all look like a raw C function...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.