문제

함수 객체를 통과하는 다음 작은 프로그램에 어떤 문제가 있습니까?

#include <iostream>
#include <functional>

void foo(const std::unary_function<const std::string&, void>& fct) {
  const std::string str = "test";
  fct(str); // error
}

class MyFct : public std::unary_function<const std::string&, void> {
public:
  void operator()(const std::string& str) const {
    std::cout << str << std::endl;
  }
};

int main(int argc, char** argv){
  MyFct f;
  foo(f);
  return 0;
}

6 행에서 다음 오류가 발생합니다.

 no match for call to 
`(const std::unary_function<const std::string&, void>) (const std::string&)'
도움이 되었습니까?

해결책

일반적인 실수. unary_function 그리고 binary_function typedefs를 추가하는 두 개의 struct입니다

argument_type
result_type

그리고 각각

first_argument_type
second_argument_type
result_type

아니 더. 그들은 기능 객체 유형의 제작자의 편의를위한 것이므로 스스로 할 필요가 없습니다. 그러나 그들은 다형성을 행동하지 않습니다. 당신이 원하는 것은 기능 객체 래퍼입니다. boost::function 생각 나다:

void foo(boost::function<void(const std::string&)> const& fct) {
  const std::string str = "test";
  fct(str); // no error anymore
}

또는 템플릿으로 만드십시오

template<typename FunctionObject>
void foo(FunctionObject const& fct) {
  const std::string str = "test";
  fct(str); // no error anymore
}

값으로 가져간 다음 사본을 반환 할 수 있습니다. foo 사용하는 경우 일부 시퀀스에 적용하십시오. 이를 통해 함수 객체가 멤버간에 일부 상태 변수를 업데이트 할 수 있습니다. for_each 그렇게하는 예입니다. 어쨌든, 나는 일반적으로 작고 복사하면 유연성이 더 커지기 때문에 가치로 받아 들일 것입니다. 그래서 나는한다

template<typename FunctionObject>
void foo(FunctionObject fct) {
  const std::string str = "test";
  fct(str); // no error anymore
}

그러면 FCT 사본을 가져 와서 어딘가에서 저장할 수 있으며 fct's operator ()는 정점이 아니며 일부 멤버 (일부 요점의 일부입니다. operator()). Const 참조로 기능 객체를 사용하는 경우 사용자가 함수를 전달할 수 있었기 때문에 일반적으로 복사 할 수 없습니다. 복사 한 다음 로컬 기능 포인터 대신 로컬로 선언을 시도합니다. 그러나 값을 값을 수락하면 함수가 통과 될 때 대신 함수 포인터가 수락되며 안전하게 복사 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top