次のコードはコンパイルされません。コンパイラは、for_each *への呼び出しで*一致する関数がないと不平を言う。なぜこれはそうですか?関数内で定義された構造体をstd :: for_eachの関数として使用できないのはなぜですか?
#include <map>
#include <algorithm>
struct Element
{
void flip() {}
};
void flip_all(std::map<Element*, Element*> input)
{
struct FlipFunctor
{
void operator() (std::pair<Element* const, Element*>& item)
{
item.second->flip();
}
};
std::for_each(input.begin(), input.end(), FlipFunctor());
}
私は機能flip_all
前struct FlipFunctor
を移動すると、コードがコンパイルされます。
完全なエラーメッセージ:
no matching function for call to ‘for_each(std::_Rb_tree_iterator<std::pair<Element* const, Element*> >, std::_Rb_tree_iterator<std::pair<Element* const, Element*> >, flip_all(std::map<Element*, Element*, std::less<Element*>, std::allocator<std::pair<Element* const, Element*> > >)::FlipFunctor)’
C++ 03:*ほとんどの場合、使用する場所の近くでアドホックなファンクタを簡単に定義できます。 :-P –