2

好吧,这是我第一次使用 lambda,我知道我可能会误用这个功能,但我想知道为什么会出现编译错误?

GameMap::MoveDirection AIPlayer::getSafeRouteTo(const GameMap::PlayerInfo& s, const Point& e)
{
    struct node : public Point
    {
        GameMap::MoveDirection parent;
        float d;
        node():Point(){};
        node(Point p) : Point(p)
        {
        };
    };
    auto lambdaFunction = [this,&e](node&left,node&right)->bool
    {
        return this->getDistance(left,e) + left.d < this->getDistance(right,e) + right.d;
    };
    priority_queue<node,vector<node>, decltype(lambdaFunction)> Q;
    //do stuff
    return GameMap::MD_None;
}

为了论证,让我说 MoveDirection 是一个枚举,而 Point 确实有一个默认构造函数。正如我通过删除该特定行评论的那样,我没有收到错误,但我真的需要它在那里。以下是 VC2010 生成的错误:

d:\program files (x86)\microsoft visual studio 10.0\vc\include\queue(225): error C2512: '`anonymous-namespace'::<lambda0>' : no appropriate default constructor available
1>          d:\program files (x86)\microsoft visual studio 10.0\vc\include\queue(223) : while compiling class template member function 'std::priority_queue<_Ty,_Container,_Pr>::priority_queue(void)'
1>          with
1>          [
1>              _Ty=AIPlayer::getSafeRouteTo::node,
1>              _Container=std::vector<AIPlayer::getSafeRouteTo::node>,
1>              _Pr=`anonymous-namespace'::<lambda0>
1>          ]
1>          c:\users\ali\documents\visual studio 2010\projects\bokhorbokhor\aiplayer.cpp(147) : see reference to class template instantiation 'std::priority_queue<_Ty,_Container,_Pr>' being compiled
1>          with
1>          [
1>              _Ty=AIPlayer::getSafeRouteTo::node,
1>              _Container=std::vector<AIPlayer::getSafeRouteTo::node>,
1>              _Pr=`anonymous-namespace'::<lambda0>
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
4

1 回答 1

6

lambda 不是默认可构造的。您必须将其传递给以下构造函数priority_queue

explicit priority_queue(const Compare& x = Compare(), Container&& = Container());

像这样:

priority_queue<node,vector<node>, decltype(lambdaFunction)> Q ( lambdaFunction );
于 2012-05-17T23:05:47.883 回答