質問

関数オブジェクトを渡し、次の小さなプログラムで何が問題なのですか?

#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を追加ちょうど2つの構造体です
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