vendredi 1 juillet 2016

C++ Function using function pointers, but not as parameters

I am learning C++. Suppose I have two functions defined outside main():

double K(const double &x)
{
    double am {1};
    double gm {sqrt(1 - x)};
    double temp {0};

    for (int i=0; i<6; ++i)
    {
        temp = am;
        am = (am + gm) * 0.5;
        gm = sqrt(temp * gm);
    }
    return PI / (am + gm);
}

and:

double sn(const double &u, const double &m)
{
    double Km {K(m)};
    double qm {exp(-PI * K(1 - m) / Km)};
    double numer {sin(PI * u * 0.5 / Km)};
    double denom {0.5};

    for (short i=1; i<5; ++i)   // i < desired_nr_of_terms
    {
        numer += pow(-1, i) * pow(qm, i*(i + 1)) * sin((i + 0.5) * PI * u / Km);
        denom += pow(-1, i) * pow(qm, i*i) * cos(i * PI * u / Km);
    }
    return pow(qm / m, 0.25) * numer / denom;
}

Would it be an improvement to call K() as a function pointer (say pntK)? The catch is that the parameter passed to K() is the same m passed to sn(), and that m is used, solo, too, inside sn(). If yes, please read further, else thank you. :-)

Do I have to make a typedef or std::function outside main() for this? Wouldn't that count as a global definition (which, as I understand, is something to avoid)?

Or, if the above is not a choice, I can define the alias (as I tried it) inside the sn() function, but then there are other functions that use pntK, how to deal with those? Define pointers inside each functions? That doesn't sound like a sane choice.

Or, if I want to pass the function pointer as a parameter to sn(), how do I deal with the fact that that both sn() and K() (or pntK()) make use of m? Would this be an "orthodox" choice?:

sn(const double &u, const double &m, std::function<double(const double&)> pntK(const double &m) = K)

If yes, then would it be safe to use it for the other functions that use K()? If not, what other choices are there?

Aucun commentaire:

Enregistrer un commentaire