2015-02-05 4 views
1
내가 std::function<type>를 사용하여 함수를 반환하기 위해 노력하고있어

를 사용하여 네임 스페이스 내에서 함수를 반환하지만 입력에 문제가 ... 코드를 볼 컴파일 시간 :C++의 표준 : 기능

LossFunction.cpp: In member function ‘std::function<float(Input, Output)>   LossFunction::getLossFunction()’: 
LossFunction.cpp:18:17: error: cannot convert ‘LossFunction::f1’ from type  ‘float (LossFunction::)(Input, Output)’ to type ‘std::function<float(Input, Output)>’ 
return this->f1; 
      ^
LossFunction.cpp:21:17: error: cannot convert ‘LossFunction::f1’ from type ‘float (LossFunction::)(Input, Output)’ to type ‘std::function<float(Input, Output)>’ 
return this->f1; 
+1

무엇이'f1'입니까? 'std :: bind'가 필요할 수도 있습니다 –

+0

멤버 함수를 정규화 된 이름으로 참조해야합니다. 그래서'& LossFunction :: f1'. – 0x499602D2

+0

'f1'의 선언문을 보여주세요 –

답변

2

문제는 네임 스페이스가 아니며 독립 실행 형 함수와 멤버 함수의 차이점입니다. 다음과 같이 자신의 첫 번째 인수의 bind을 독립 기능 std::function의 생성자에 전달 될 수 있지만, 멤버 함수가 필요합니다

switch (this->functionType){ 
    case 0: 
     return std::bind(&LossFunction::f1, this, _1, _2); 
     break; 
    default: 
     return std::bind(&LossFunction::f1, this, _1, _2); 
     break; 
} 
+1

'네임 스페이스 std :: placeholders를 사용한다고 가정하면'std :: bind (& LossFunction :: f1, this, _1, _2);'가 필요합니다 : –

+0

완벽하게 작동했습니다 ... 감사합니다 도움을 청하고 ... – Tim

1

그것은 f1LossFunction의 멤버 함수라는 오류 메시지에서 나타납니다. 그것은 독립 기능이라면이 작동,하지만 멤버 함수는 std::bind를 사용하거나 같은 람다를 사용하여 std::function의 객체는 바인딩 할 수 호출 할 포인터 및 저장을 필요로 :

return [this](Input in, Output out){ return f1(in, out); }; 

또는

return std::bind(&LossFunction::f1, this);