2010-06-24 2 views
1

함수 서명이 일치하는 멤버 함수로 전달하는 간단한 방법이 있습니까?함수 서명이 일치하는 멤버 함수로 전달하는 간단한 방법이 있습니까?

typedef std::tr1::function<int(int,int,int,int)> TheFn; 
class C 
{ 
    int MemberFn(int,int,int,int) { return 0; } 

    TheFn getFn() { 
     //is there a simpler way to write the following line? 
     return [this](int a,int b,int c,int d){ return this->MemberFn(a,b,c,d); }; 
    } 
}; 
+0

아마도 std :: mem_fun이 구현되는 방법을 살펴봄으로써 약간의 통찰력을 얻을 수 있을까요? – Cogwheel

+0

당신이 정말로 여기에서 이루고자하는 것을 명확히해야한다고 생각합니다. 나는 당신이 물어 본 것 (본질적으로)이 가능하다고 생각하지는 않지만 근본적인 문제가 그것이 무엇인지를 알게되면 여전히 해결 될 수 있다고 생각하기에 충분히 가깝습니다. –

+0

내 응용 프로그램에는 선택적인 setter 및 getters로 초기화되는 수백 개의 '스마트 통신 블록'이 있습니다. 대개의 경우 이들은 특정 객체에 대해 동일한 서명을 가진 멤버 함수에 전달됩니다. 나는 MagicBind (this, & MemberFn)와 같은 것을 기대하고 있었다. 나는 단지 코드 노이즈를 줄이려고했다. – jyoung

답변

1

bind을 사용해 보셨습니까?

// C++0x update 
struct test { 
    void f(int, int, int, int); 
}; 
int main() 
{ 
    std::function<void (int,int,int,int)> fn; 
    test t; 
    fn = std::bind(&t::f, &t, 
      std::placeholders::_1, 
      std::placeholders::_2, 
      std::placeholders::_3, 
      std::placeholders::_4); 
    fn(1, 2, 3, 4); // t.f(1, 2, 3, 4) 
} 

나는 모든 요소의 완전한 자격을 왼쪽,하지만 std::placeholders 너무 많은 시간이 정말로 가독성을 도움이되지 않습니다 적용 ... 나는 using std::placeholders 전혀 해치지 않을 것 같아요

using std::placeholders; 
fn = std::bind(&t::f, &t, _1, _2, _3, _4); 

편집을 :이 동일한 기능을 가진 명확 수 있도록, 질문 코드에 그것을 가깝게 만들려면 그 원래의 코드 : 당신이 보에서 볼 수 있듯이

typedef std::function<int(int,int,int,int)> TheFn; 
class C { 
    int MemberFn(int, int, int, int) { return 0; } 
public: 
    int MemberFn2(int,int,int,int) { return 2; } 
    TheFn getFn() { 
     using std::placeholders; 
     return std::bind(&C::MemberFn, this, _1, _2, _3, _4); 
    } 
}; 
int main() { 
    C instance; 
    TheFn fn1 = instance.getFn(); 
    std::cout << fn1(1, 2, 3, 4) << std::endl; // 0 

    using std::placeholders; 
    TheFn fn2 = std::bind(&C::MemberFn2, &instance, _1, _2, _3, _4); 
    std::cout << fn2(1, 2, 3, 4) << std::endl; 
} 

당신이 똑같이하고있는 경우. 예를 들어 비공개 및 공개 메서드를 사용하여 bind 일 때 구성원 메서드 액세스 수준이 호출 위치가 아니라 바인딩 위치에서 검사되는 것을 보여줍니다. 따라서 MemberFn이 클래스 내에서 비공개 인 경우에도 바인드 된 펑터를 통해 호출 할 수 있습니다. 회원이 공개이면 실제로 수업 외부에서 바인딩 할 수 있습니다.

0

부스트 무언가 :: 람다를 만들 수도 있지만, 당신은 쉽게 명시 적으로 타입 정의보다 뒤에 반환 유형을 사용하여 찾을 수 있습니다 것을 제외하고 현실에서, 나는하지 좋을 것. 추가로, 내가 아는 한, 당신이 특별한 상황으로 이것을 잡았을 때, 람다는 멤버 람다가되고, 명시 적으로 이것을 필요로하지 않는다.

관련 문제