2010-07-26 5 views
3

내 혼동이 코드처럼 :boost :: bind는 제공된 서명과 일치하지 않지만 제대로 작동합니까?

#include "stdafx.h" 
#include <boost/bind.hpp> 

using namespace std; 

void fool(std::string s) 
{ 
std::cout<<s<<endl; 
} 

void fool2() 
{ 
std::cout<<"test2 called\n"<<endl; 
} 

void fool3(std::string s1,std::string s2) 
{ 
std::cout<<"test3 called\n"<<endl; 
} 

typedef boost::function<void(std::string)> myHandler; 
void mywait(myHandler handler) 
{ 
handler("hello my wait"); 
} 

int main() 
{ 
mywait(boost::bind(fool,_1)); //it works fine as expected. 

mywait(boost::bind(fool2)); //how it works? fool2 doesnot match the signature of "boost::function<void(std::string)>" 

//mywait(boost::bind(fool3,_1,_2)); //if fool2 works fine, why this not work? 
return 0; 
} 

추적 링크가 같은 질문이다.

http://forums.opensuse.org/english/development/programming-scripting/441878-how-can-boost-bind-swallow-argument-member-function.html

난 그냥 문서를 읽어

: 그 그냥 작동 말할 바인드

에 대한 부스트 문서

[부스트 바인딩 도서관 당신의 C++ 프로그램을 개선 할 수있는 방법,하지만 난 그렇게하지 왜 그런지 안다. 나는 여전히 혼란 스럽다.

불쌍한 내 영어에 대해 미안. 나는 분명히 설명했다.

답변

1

부스트에 대한 깔끔한 것 중 하나는 바로 기능을 약간 다른 서명으로 "마사지"하는 기능입니다.

예를 들어, 사용자가 명시 적으로 두 번째 매개 변수에 대한 값을 제공하여 fool3 예를 들어 작업을 할 수 있습니다 : a로 (사용되지 않는 함수에 전달되는

mywait(boost::bind(fool3, _1, "extra parameter")); 
// or even: 
mywait(boost::bind(fool3, "extra parameter", _1)); 

모든 매개 변수를 _ n)는 함수가 호출 될 때 단순히 무시됩니다.

+0

"Boost.Bind는 기능이 약간 다른 시그니처에"마사지 "하는 능력을 가지고 있다는 것을 알고 있습니다.", 그러나 나는 그게 어떻게 일어 났는지 모릅니다. 나에게 너무 마술 같아. 그 메커니즘을 알 수 있니? 답장을 보내 주셔서 감사합니다. – Haozes

+1

그것은 일종의 마법입니다 :-) [이 이전 질문] (http://stackoverflow.com/questions/112738/how-does-boost-bind-work-behind-the-scenes-in-general) goes some 귀하의 질문에 답변하는 방법 ... –

관련 문제