什么是错的传递函数对象以下的小程序?

#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_functionbinary_function只是两个结构即添加的typedef

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的运营商()可以非const和更新一些成员(这是operator()整点的一部分)。请记住,如果你把一个函数对象通过const引用,则无法复制通常它,因为用户可能已经过去了一个功能。复制然后它会尝试在本地声明函数,而不是本地函数指针。然而,通过值接受将接受一个函数指针,而不是当一个函数被传递,这可以安全地被复制。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top