通过构造函数初始化成员函数

Initialize member functions via constructor

本文关键字:成员 函数 初始化 构造函数      更新时间:2023-10-16

也许我对这个问题有点不了解,但有可能通过构造函数定义成员函数吗?

在我的案例中,我试图编写一个类来执行稳健的模型拟合(使用RANSAC)。我希望这可以推广到不同类型的模型中。例如,我可以使用它来确定对一组3D点的平面的估计。或者,也许我可以确定两组点之间的转换。在这两个例子中,可能需要不同的误差函数和不同的拟合函数。静态函数调用可能看起来像,而不是使用类

model = estimate(data, &fittingFunc, &errorFunc);

我想知道我是否可以为那些模块化函数提供成员实例?

类似的东西

class Estimator
{
private:
// estimation params
double errorFunc(std::vector<dtype>, double threshold); // Leave this unimplemented
double fittingFunc(std::vector<dtype>, Parameters p); // Leave this unimplemented
public:
Estimator(void (*fittingFunc(std::vector<dtype>, Parameters), void (*errorFunc(std::vector<dtype>, double));
dtype estimate(data); // Estimates model of type dtype. Gets implemented
};
Estimator::Estimator(void (*fittingFunc(std::vector<dtype>, Parameters), void (*errorFunc(std::vector<dtype>, double))
{
fittingFunc = fittingFunc;
errorFunc = errorFunc;
}

我想我已经在我的例子中破坏了正确的语法,但我希望问题是清楚的。基本上,我在问:构造函数是否可以接受函数指针作为参数,并将其分配为成员函数的实现

第二,即使这是可能的,它是否被认为是糟糕的形式?

更新:如果有帮助的话,这里是用于稳健估计的MATLAB代码,它具有我希望在C++中复制的这种可推广结构

构造函数是否可以接受函数指针作为参数,并将其分配为成员函数的实现?

否。不是成员函数。但是您当然可以拥有公共成员函数指针:

class Estimator
{
public:
double (*errorFunc)(std::vector<dtype>, double threshold);
double (*fittingFunc)(std::vector<dtype>, Parameters p);
public:
Estimator(void (*fittingFunc(std::vector<dtype>, Parameters), void (*errorFunc(std::vector<dtype>, double))
: errorFunc(errorFunc)
, fittingFunc(fittingFunc)
{ }
dtype estimate(data);    
};

为了获得更好(或更安全)的接口,您可以将函数指针设为private,并拥有一个只需调用它们的公共成员函数。


更一般地说,如果您对开销满意,您可以拥有类型为std::function<double(std::vector<dtype>, double)>std::function<double(std::vector<dtype>, Parameters)>的成员,然后您可以使用更广泛的可调用对象(函数指针,但也包括lambda、绑定成员函数等)

是的,您可以为拟合和误差函数提供算法。您可以使用指向函数的指针来完成此操作。还有一个更好的解决方案,在标准标头中,您可以找到模板std::函数,它可以用指向函数的指针构造,也可以用函子或lambda表达式构造。

你的课应该是这样的:

#include <functional>
class Estimator
{
private:
// estimation params
using error_func_type =   std::function<double(std::vector<dtype>,double)>;
using fitting_func_type = std::function<double(std::vector<dtype>,Parameters p)>;
fitting_func_type fittingFunc;
error_func_type errorFunc;

public:
Estimator(fitting_funct_type fit, error_funct_type err)
:fittingFunc(fit),errorFunc(err){}
dtype estimate(data); // Estimates model of type dtype. Gets implemented
};