C ++ lambda错误:没有合适的默认构造函数可用

时间:2022-11-16 19:34:33

Well this is my first experience with lambda, and I know I might be misusing this feature but I'm wondering why should I get a compile error?

这是我第一次使用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;
}

and for the sake of argument let me say that MoveDirection is an enum, and Point does have a default constructor. as I commented by removing that specific line I don't get the error but I really need it to be there. here are the errors VC2010 is generating:

为了说明,让我说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 ==========

1 个解决方案

#1


4  

The lambda is not default constructible. You have to pass it to this constructor of the priority_queue:

lambda不是默认的可构造的。您必须将它传递给priority_queue的此构造函数:

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

Like this:

priority_queue<node,vector<node>, decltype(lambdaFunction)> Q ( lambdaFunction );

#1


4  

The lambda is not default constructible. You have to pass it to this constructor of the priority_queue:

lambda不是默认的可构造的。您必须将它传递给priority_queue的此构造函数:

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

Like this:

priority_queue<node,vector<node>, decltype(lambdaFunction)> Q ( lambdaFunction );