以下代码不会编译。编译器抱怨 *无匹配函数以供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());
}

当我移动时 struct FlipFunctor 功能之前 flip_all, ,代码编译。

完整错误消息:

无匹配函数呼叫'for_each(std :: _ rb_tree_iterator u003Cstd::pairu003CElement* const, Element*> >,std :: _ rb_tree_iterator u003Cstd::pairu003CElement* const, Element*> >,flip_all(std :: map u003CElement*, Element*, std::lessu003CElement*> ,std ::分配器u003Cstd::pairu003CElement* const, Element*> >>):: flipfunctor)''

有帮助吗?

解决方案

std::for_each 是函数模板;模板参数之一是函数参数的类型。

您不能将本地类型用作模板参数。这只是该语言当前的限制。在C ++,C ++ 0x的即将进行的修订中,该限制被删除,因此您可以将本地类型用作模板参数。

Visual C ++ 2010已经支持将本地类用作模板参数的使用;其他编译器的支持可能会有所不同。我猜想任何支持C ++ 0x lambdas的编译器也将支持将本地类用作模板参数的使用(这可能不是完全正确的,但这是有道理的)。

其他提示

当我尝试编译您的代码时,我会遇到不同的错误:

错误:'flip_all(__ gnu_debug_def :: map,std :: allocator >>):: flipfunctor'使用local type'flip_all(__ gnu_debug_def :: map,std,std,std,std :: Arlocator>:sallocator>>):: flipfunctor'''

实际上是可以预料的,因为局部类型(例如在此处的flipfunctor)具有内部链接,并且模板类型必须具有外部链接。由于std :: for_each的第三个参数 模板,您无法将功能局部类型传递给它。

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