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

mar*_*man 1 c++ constructor function-pointers class

也许我对这个问题很陌生,但是是否可以通过构造函数定义成员函数?

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

model = estimate(data, &fittingFunc, &errorFunc);
Run Code Online (Sandbox Code Playgroud)

我想知道我是否可以为这些模块化功能提供成员实例?

就像是

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;
}
Run Code Online (Sandbox Code Playgroud)

我想我已经在我的例子中混杂了正确的语法,但我希望这个问题很清楚。基本上我在问:构造函数能否接受函数指针作为参数并将它们分配为成员函数的实现?

其次,即使这是可能的,它是否被认为是不良形式?

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

Bar*_*rry 5

构造函数能否接受函数指针作为参数并将它们分配为成员函数的实现?

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

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);    
};
Run Code Online (Sandbox Code Playgroud)

对于更好(或更安全)的接口,您可以创建函数指针private并拥有一个简单地调用它们的公共成员函数。


更一般地,如果你没事用开销,你可以有类型的成员std::function<double(std::vector<dtype>, double)>std::function<double(std::vector<dtype>, Parameters)>,然后你可以使用更多种类的可调用的(函数指针,也是lambda表达式,绑定成员函数等)

  • @k-5 讨论超出了评论的范围,[见这里](http://en.cppreference.com/w/cpp/utility/functional/function) (2认同)