2017-02-06 145 views
0

也许我是用这个问题离开左边的领域,但是有可能通过构造函数定义成员函数吗?通过构造函数初始化成员函数

在我的情况下,我想写一个类来执行健壮的模型拟合(使用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; 
} 

我想我已经在我的例子bastardized正确的语法,但我希望这个问题是清楚的。基本上我问:构造函数是否可以接受函数指针作为参数并将它们赋值为成员函数的实现?

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

更新:如果有帮助,here is MATLAB code for robust estimation有这种一般化结构的我希望能复制在C++

+0

的回答你的问题是**是**。并在'double'中更正你的代码;'和这个分号是为了什么? –

+0

@ k-five:错字,对不起。是的,这可能吗?或者是的,这是不好的形式?或两者? – marcman

+0

尽管[*** Pimpl idiom ***](http://stackoverflow.com/questions/60570/why-should-the-pimpl-idiom-be-used)可能是更好的方法。 –

回答

4

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

编号不作为成员功能。但是,你当然可以有公共成员函数指针

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表达式,绑定的成员函数,等等)

+0

这似乎是我想到的,尤其是在私人指针方面。我会尝试一下,如果有效,请接受 – marcman

+0

谢谢。我正在努力寻找它允许的标准(http://ideone.com/r4rr2j)以及为什么我无法得到它的工作,这要归功于评论中强调的Yeses。 – user4581301

+0

@ M.M我建议。 – Barry

1

是的,你可以提供你的拟合和错误函数的算法。你可以使用指向函数的方法做到这一点。并且有一个更好的解决方案,在标准头文件中,您将找到模板std :: function,它可以用函数指针构造,也可以用函数或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 

}; 
相关问题