기본 컴퓨팅 (함수)을 제공해야하지만 컴파일시 사용자가 직접 제공 할 수있는 라이브러리를 작성한다고 가정 해보십시오. 예를 들어, 라이브러리가 인수 시간 3을 반환하는 함수를 제공하지만 사용자가 자신의 함수를 제공 할 수 있다고 가정 해보십시오. also here 제안으로,functor : 클래스의 std :: function 랩
float myFunction(float v) // the function the user needs
{
return v*2;
}
int main()
{
FuncWrapper f;
cout << "default: " << f(2) << endl; // should print "6"
f.AssignFunction(myFunction);
cout << "now is: " << f(2) << endl; // should print "4"
}
그래서 나는 std::function
을 감싸는 펑 FuncWrapper
을 구축해야 :
struct FuncWrapper
{
std::function<float(float)> foo; // the function used
float def(float v) // the default behaviour member function definition
{
return v*3;
}
float operator()(float v) // call of function
{
return foo(v);
}
void AssignFunction(float (*uf)(float)) { foo = uf; }
// constructor: initializes to default function
FuncWrapper() : foo(&FuncWrapper::def) {}
};
내 컴퓨터에
는 다음 프로그램 (A MWE로 볼 수)를 고려 (gcc 4.6.3)을 -std=c++0x
으로 바꾸면 this other answer에 명시된 사람이 읽을 수없는 오류 메시지가 표시됩니다. 편의를 위해 코드는 runnable here입니다. 4.8 GCC 것 같다, 그리고 생성자 좋아하지 않는다 (다른 오류들 사이를 ...) :
main.cpp: In constructor 'FuncWrapper::FuncWrapper()':
main.cpp:27:64: error: no matching function for call to 'std::function<float(float)>::function(float (FuncWrapper::*)(float))'
왜이 할당이 불법? 이 주제에 대해 searched이 있는데, 아마도 잘못된 키워드 일 수 있지만 관련성이 발견되지 않았습니다.
단서가 있습니까? 또는 더 간단한 해결책, 어쩌면 std::function
없이 그러나 기능 포인터로? 귀하의 예제 코드에서
FuncWrapper :: def는 정적이어야합니다 – Kiroxas