C++ External function with pointer to function as parameter, used inside a class with a member function

时光总嘲笑我的痴心妄想 提交于 2019-12-10 17:42:13

问题


Fairly new to C++. Suppose I have a class:

class A
{
private:
    double m_x, m_y;
public:
    A(double x, double y): m_x {x}
    {
        m_y = extF(m_x, y, *intF);
    }

    double intF(double x) { return 2*x; }
};

And it makes use of an external global function, defined elsewhere:

double extF(double x, double y, std::function<double(double)> f)
{
    if (x*y < 0)
        return f(x);
    else
        return f(y);
}

Formulas are bogus. This does not compile. I tried simple intF, A::*intF, &A::intF, even some unorthodox combinations, but that's just guessing. The problem is that class A is not the only one which makes use of the global external function and it's something that should be able to be a user choice at runtime. Searches revealed some answers saying it's not possible to make a pointer to a member function like this because it needs instantiation(?), but I found no solutions. Can this be done? If yes, how?


Edit: Additional question: how can the pointer to member function be done if the member function is const double f(...) const?


回答1:


One variant is just to use lambda:

class A
{
private:
    double m_x, m_y;
public:
    A(double x, double y): m_x {x}
    {
         m_y = extF(m_x, y, [&](double d){ return intF(d);});
    }

    double intF(double x) { return 2*x; }
};

Another variant is to use lambda and std::mem_fn (omitting the rest code of your class):

A(double x, double y): m_x {x}
{
    auto fn = std::mem_fn(&A::intF);
    m_y = extF(m_x, y, [&](double d) {return fn(this, d);});
}

And finally you may get rid of lambdas if you bind the object parameter of member function pointer:

A(double x, double y): m_x {x}
{
    auto fn1 = std::bind(std::mem_fn(&A::intF), this, std::placeholders::_1);
    m_y = extF(m_x, y, fn1);
}

All these also work with constant member functions.




回答2:


You could use std::bind to bind the member function.

A(double x, double y): m_x {x}
{
    using namespace std::placeholders;
    m_y = extF(m_x, y, std::bind(&A::intF, this, _1));
}

Or use a lambda.

A(double x, double y): m_x {x}
{
    m_y = extF(m_x, y, [this](double d) { return intF(d); });
}

BTW: It works well with const member function too, which doesn't matter here.

LIVE



来源:https://stackoverflow.com/questions/39053877/c-external-function-with-pointer-to-function-as-parameter-used-inside-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!