算术表达式可以作为参数传递给函数以描述其中的逻辑吗?

gat*_*tor 0 c++ polymorphism expression class c++03

我正在可视化Mandelbrot集以及其他一些分形,并且有很多重复的代码,但是没有代码重用。

我正在使用的功能之一如下:

/**
 * determines whether a pixel lies in the set
 * @params x, y - x and y coordinates on R/I axes
 * @param c - a complex number
 */
void calculateSet(int x, int y, Complex c) {
    Complex z = c.clone();
    int n = 0;
    for (; n < maxDepth; n++) {
        if (z.dis() > 4) { break; }
        z = z^2 + c;
    }
    // some code using n to color the set
}
Run Code Online (Sandbox Code Playgroud)

这遵循Mandelbrot集:

z_(n+1) = z_n^2 + c
Run Code Online (Sandbox Code Playgroud)

但是,请查看“燃烧之船”集的相关代码:

void calculateSet(int x, int y, Complex c) {
    Complex z = c.clone();
    int n = 0;
    for (; n < maxDepth; n++) {
        if (z.dis() > 4) { break; }
        z = abs(z)^2 + c; // ***
    }
    // follows z_(n+1) = abs(z_1)^2 + c
}
Run Code Online (Sandbox Code Playgroud)

加注星号的所有代码都相同。现在,我为MandelbrotBurningShip和其他几个提供了单独的类,唯一的不同是那一行。

有没有一种方法可以定义此表达式并将其传递给通用Set类?

一些伪代码:

class Set {
    // ...
    Set(Type expression) {
        // ...
        // x, y, c initialized
        // ...
        calculateSet(x, y, c, expression);
    }
    void calculateSet(int x, int y, Complex c, Type e) {
        Complex z = c.clone();
        int n = 0;
        for (; n < maxDepth; n++) {
            if (z.dis() > 4) { break; }
            z = e;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

我可以用它Set来描述任何我想要的集合吗?

Set mandelbrot = Set(Type("z^2 + c"));
Set burningship = Set(Type("abs(z)^2 + c"));
// etc
Run Code Online (Sandbox Code Playgroud)

我可以使用if/else语句仅具有一个类,但它不是通用的。

dru*_*nly 5

由于限于C ++ 03,因此可以相对轻松地使用函数指针。

Complex mandlebrotCompute(Complex z, Complex c) {
  return z*z + c;
}

void calculateSet(int x, int y, Complex c, Complex (*func)(Complex, Complex)) {
    Complex z = c.clone();
    int n = 0;
    for (; n < maxDepth; n++) {
        if (z.dis() > 4) { break; }
        z = func(z, c);
    }
}
Run Code Online (Sandbox Code Playgroud)

它的用法如下:

Complex foo;
calculateSet(1, 2, foo, mandlebrotCompute);
Run Code Online (Sandbox Code Playgroud)

为函数指针使用typedef可能有助于使代码更简洁