2

함수에 대한 일반 포인터를 선언 할 수 없습니다.(member?) 함수에 대한 C++ 일반 포인터

이이 개 기능을 갖는 호출 할 :

void myfunc1(std::string str) 
{ 
    std::cout << str << std::endl; 
} 
struct X 
{ 
     void f(std::string str){ std::cout<< str << std::endl;} 
}; 

이 두 기능 발신자 :

typedef void (*userhandler_t) (std::string); 
struct example 
{ 
    userhandler_t userhandler_; 

    example(userhandler_t userhandler): userhandler_(userhandler){} 

    void call(std::string str) 
    { 
     userhandler_(str); 
    } 
}; 
template<typename func_t> 
void justfunc(func_t func) 
{ 
    func("hello, works!"); 
} 

나는 그들이주는 멤버 함수를 호출하는 부스트 :: 바인드로 사용하려고 오류를 컴파일합니다.

이 작동합니다

example e1(&myfunc1); 
e1.call("hello, world!"); 
justfunc(&myfunc1); 

이되지 않습니다이 예상되는 어떻게

X x; 
example e2(boost::bind(&X::f, &x, _1)); 
e2.call("hello, world2!"); 
justfunc(boost::bind(&X::f, &x, _1)); 

할 수 있나요?

+0

리턴 유형이나 'X :: f'의 인수 유형이 'example'에 필요한 것과 일치하지 않습니다. 당신은 무엇을 기대 했습니까? –

답변

7

boost::bind은 실제 함수 포인터가 아닌 함수처럼 동작하는 객체를 만듭니다. Boost.Function 라이브러리를 사용하여 boost::bind의 결과를 보유하십시오.

struct example 
{ 
    boost::function<void(std::string)> userhandler_; 
    ... 
}; 
+0

Marcelo가 말했듯이'boost :: bind'는 _function 포인터 _가 아닌 __function objects__ (일명 _functors_)를 만듭니다. +1. – sbi

+0

Thx, 나는 문서에서 그것을 놓쳤다. (여기에 있었다 : http://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html#with_boost_function) –