2010-05-08 2 views
1

먼저 의사 코드 (자바 스크립트)를 사용하여 달성하려는 것을 설명해 드리겠습니다.인라인 콜백 함수를 인수로 지정하십시오.

// Declare our function that takes a callback as as an argument, and calls the callback with true. 
B(func) { func(true); } 

// Call the function 
B(function(bool success) { /* code that uses success */ }); 

나는 이것이 모두를 말하고 싶습니다. 그렇지 않다면 제 질문에 대해 의견을 말하면서 제 문제를 명확히하기 위해 조금 더 작성할 수 있습니다.

내가 원하는 것은 C++에서 이와 같은 코드를 사용하는 것이다.

람다 함수를 사용하려고했지만 매개 변수 유형을 지정할 수 없습니다.

답변

1

컴파일러가 Visual Studio 2010 또는 GCC 4.5와 같은 최신 버전 인 경우 새 C++ 표준의 새 기능을 사용할 수 있습니다.이 기능은 현재 비준 중이며 조만간 게시해야합니다.

Visual Studio에서이 기능을 사용하려면 어떻게해야할지 모르지만 MSDN 또는 내부 도움말에서 잘 설명해야합니다.

GCC 4.5의 경우 새로운 기능을 사용하려면 -std=c++0x 옵션을 추가하기 만하면됩니다. 이러한 기능의

하나 인 Lambda syntax :

template <typename F> 
void func_with_callback(F f) { 
    f(true); 
} 

int main() { 
    func_with_callback([](bool t){ if(t) cout << "lambda called" << endl; }); 
} 

당신이 현대 컴파일러에 액세스 할 수없는 경우에는 유사하게 수행 할 수 부스트 : : 람다 같은 펑터와 라이브러리 등의 기술을 사용할 수 있습니다 .

+0

이것은 내가 찾고있는 것입니다. 나는 이미 템플릿과 람다 식으로 주변을 둘러 보았지만 작동시키지 못했습니다. 참고로, VS2010에서는 추가 변경없이이 기능을 사용합니다. –

2

EDIT : 질문을 다시 읽으면 C++에서 익명의 함수를 찾고있는 것처럼 보입니다. 그게 네가 원하는 것이라면 불행하게도 그 언어는 그 기능을 지원하지 않는다. C++에서는 현재 이러한 종류의 것들을 좀더 장황하게 요구합니다. 만약 당신이 무엇보다 boost::lamda이 이미 필요하다면, 어쨌든 정상적인 기능으로 분리해야합니다.


C 및 C++에서이 작업은 함수 포인터 또는 펑터와 템플릿 (C++에만 해당)을 사용하여 수행됩니다.

예를 들어

는 C의 방법을 사용

//Define a functor. A functor is nothing but a class which overloads 
//operator(). Inheriting from std::binary_function allows your functor 
//to operate cleanly with STL algorithms. 
struct MyFunctor : public std::binary_function<int, int, bool> 
{ 
    bool operator()(int a, int b) { 
     return a < b; 
    }; 
}; 

//Define a template which takes a functor type. Your functor should be 
//should be passed by value into the target function, and a functor should 
//not have internal state, making this copy cheap. 
template <typename Func_T> 
void MyFunctionUsingACallback(Func_T functor) 
{ 
    if (functor(a, b)) 
     //Do something 
    else 
     //Do something else 
} 

//Example usage. 
int main() 
{ 
    MyFunctionUsingACallback(MyFunctor()); 
} 

(함수 포인터)합니다 (C++ 방법 (펑)를 사용하여) :

//Create a typedef for a function pointer type taking a pair of ints and 
//returning a boolean value. 
typedef bool (*Functor_T)(int, int); 

//An example callback function. 
bool MyFunctor(int a, int b) 
{ 
    return a < b; 
} 

//Note that you use the typedef'd function here. 
void MyFunctionUsingACallback(Functor_T functor) 
{ 
    if (functor(a, b)) 
     //Do something 
    else 
     //Do something else 
} 

//Example usage. 
int main() 
{ 
    MyFunctionUsingACallback(MyFunctor); 
} 

참고가 수 있기 때문에 당신이 C++ 방법을 선호한다 컴파일러는 인라이닝과 관련하여 더 현명한 결정을 내립니다. 어떤 이유로 든 사용자는 C 하위 집합으로 제한됩니다.