问题描述
是C ++的新手.假设我有一堂课:
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);
}
配方是假的.这不会编译.我尝试了简单的intF
,A::*intF
,&A::intF
,甚至是一些非正统的组合,但这只是猜测.问题在于,类A
并不是唯一一个使用全局外部函数的类,它应该可以在运行时成为用户的选择.搜索显示了一些答案,表明不可能像这样的成员函数创建指针,因为它需要实例化(?),但是我没有找到解决方案.能做到吗?如果是,怎么办?
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?
另一个问题:如果成员函数为const double f(...) const
,如何完成指向成员函数的指针?
Additional question: how can the pointer to member function be done if the member function is const double f(...) const
?
推荐答案
一个变种就是使用lambda:
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; }
};
另一种变体是使用lambda和 std::mem_fn
(省略您课程的其余代码):
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);});
}
最后,如果您绑定,则可能会摆脱lambda成员函数指针的对象参数:
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.
这篇关于C ++外部函数,带有指向函数作为参数的指针,在带有成员函数的类内部使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!