为什么一个函数内部定义的结构体不能用作std :: for_each的函子? [英] Why can't a struct defined inside a function be used as functor to std::for_each?

查看:375
本文介绍了为什么一个函数内部定义的结构体不能用作std :: for_each的函子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将无法编译。编译器抱怨*没有匹配的函数调用for_each *。为什么会这样?

The following code won't compile. The compiler complains about *no matching function for call to for_each*. Why is this so?

#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

When I move struct FlipFunctor before function flip_all, the code compiles.

完整的错误消息:


没有匹配函数调用'for_each(std :: _ Rb_tree_iterator< std :: pair< Element * const,Element *>>,std :: _ Rb_tree_iterator& :: pair< Element * const,Element *>>,flip_all(std :: map< Element *,Element *,std :: less< Element *> ;, std :: allocator< std :: pair& const; Element *>>>):: 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)’


推荐答案

code> std :: for_each 是一个函数模板;其中一个模板参数是函数参数的类型。

std::for_each is a function template; one of the template parameters is the type of the function argument.

不能使用局部类型作为模板参数。这只是当前语言中的一个限制。在即将到来的C ++版本C ++ 0x中,此限制被删除,因此您可以使用本地类型作为模板参数。

You cannot use a local type as a template argument. It's just a restriction currently in the language. In the forthcoming revision of C++, C++0x, this restriction is removed, so you can use local types as template arguments.

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

Visual C++ 2010 already supports the use of local classes as template arguments; support in other compilers may vary. I'd guess that any compiler that supports C++0x lambdas would also support the use of local classes as template arguments (this may not be entirely true, but it would make sense).

这篇关于为什么一个函数内部定义的结构体不能用作std :: for_each的函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆