2017-02-06 5 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; 
} 

같은

뭔가 내가 내 예에 적절한 구문을 놨 한 상상,하지만 문제는 분명하다 바랍니다. 기본적으로 묻는 오전 : 생성자 인수로 함수 포인터를 받아들이고 멤버 함수의 구현을 할당 할 수 있습니까?

두 번째로 이것이 가능하더라도 나쁜 형태로 간주됩니까?

UPDATE : 그것은, 내가 C++

+0

질문에 대한 대답은 ** 예 **입니다 :

클래스는 다음과 같이 될 것이다. 'double에서 코드를 수정하십시오. '; 그리고이 세미콜론은 무엇을위한 것입니까? –

+0

@ k-five : 오타, 미안. 그리고 네, 가능합니까? 아니면 그렇습니다. 나쁜 형태입니까? 아니면 둘다? – marcman

+0

[*** Pimpl idiom ***] (http://stackoverflow.com/questions/60570/why-should-the-pimpl-idiom-be-used)이 더 나은 접근 방법 일 수 있습니다. –

답변

4

인수로 함수 포인터를 생성자를 수용 할 수있는 복제 및 멤버 함수의 구현 수를 할당하는 바라고 있어요 일반화 구조의이 종류가 있습니다 here is MATLAB code for robust estimation을 도움이된다면 ?

번호 없음 기능. , 더 좋은 (또는 안전) 인터페이스의

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)>의 구성원을 가질 수 있고 다음 (함수 포인터를 callables보다 다양한 사용할 수 있습니다뿐만 아니라, 람다, 바인딩 멤버 함수, etc.)

+0

이것은 특히 개인 포인터를 염두에두고있는 것으로 보입니다. 나는 그것을 시도 할 것이고 그것이 작동한다면 이것을 받아 들여야한다. – marcman

+0

고마워. 나는 표준에서 그것이 [이와 비슷한 것] (http://ideone.com/r4rr2j)을 허용하는 곳을 찾기 위해 열심히 노력하고 있었고, 코멘트에서 중요한 예스 덕분에 왜 그것을 작동시키지 못하게 되었습니까. – user4581301

+0

@ M.M 나는 그것을 제안했다. – Barry

1

예 피팅과 오류 기능에 대한 알고리즘을 제공 할 수 있습니다. 함수 포인터를 사용하면됩니다. 표준 헤더에는 함수 포인터뿐만 아니라 펑터 또는 람다 (lambda) 표현식으로도 생성 할 수있는 std :: function 템플릿이 있습니다.

#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 

};