Question

I'm working on a function that takes a well known range of arguments, but I don't want to write many different functions for each case. Is there a way to define let's say a "pattern" of function and make the precompiler generate functions based on this pattern?

Example. I have following function:

int addition_in_range_of_10 (int a, int b) {    return a+b; }

I want to generate following functions:

int addition_in_range_of_10_1_1 () {
    return 2;
}

int addition_in_range_of_10_1_2 () {
    return 3;
}

int addition_in_range_of_10_1_3 () {
    return 4;
}

...

int addition_in_range_of_10_10_10 () {
    return 20;
}

I want run these functions using pointer to function:

int (*funp)();
if(...) {
    funp = addition_in_range_of_10_1_3;
}
funp();

Right now I wrote my own app that do from below template functions enumerated above but it is not comfortable to copy code to my app and then result to cpp file and then compile. I want to have it automated.

//{A=1,2,3,4,5,6,7,8,9,10;B=1,2,3,4,5,6,7,8,9,10}
int addition_in_range_of_10_{A}_{B} () {
    return {A}+{B};
}

Here is my question. Is there any preprocessing library, mechanism, or something what could do it automatically?

I just want to remove variables from code because of performance. Those functions are a lot of more complicated and works a lot better if have constants instead of variables, and because those variables uses only some well known values I would like to change them to constants instead of variables.

Was it helpful?

Solution 2

Without any special tools you can do this:

#define MYADD(A,B) \
    int addition_in_range_of_10_##A##_##B () { \
        return A+B; \
    }

#define MYADD2(A) \
    MYADD(A,1) \
    MYADD(A,2) \
    ...
    MYADD(A,10)

MYADD2(1)
MYADD2(2)
...
MYADD2(10)

But boost preprocessor can help you to make this more compact. Have a look at BOOST_PP_LOCAL_ITERATE.

OTHER TIPS

for C++

#include <iostream>

template <int A, int B>
int addition_in_range_of_10(void){
    return A + B;
}

int main(){
    int (*funp)();
    if(1) {
        funp = addition_in_range_of_10<1,3>;
    }
    std::cout << funp() << std::endl;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top