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 하위 집합으로 제한됩니다.
이것은 내가 찾고있는 것입니다. 나는 이미 템플릿과 람다 식으로 주변을 둘러 보았지만 작동시키지 못했습니다. 참고로, VS2010에서는 추가 변경없이이 기능을 사용합니다. –