无法将lambda转换为std :: function

Dan*_*man 0 c++ lambda mingw c++11 visual-studio-2012

我在尝试创建API时遇到MiniGW问题.这在MSVC11(Visual Studio 2012 C++编译器)中工作正常.我的编译器(我相信)设置正确QMAKE_CXXFLAGS += -std=c++0x,毕竟我有一个lambda错误消息.

有关更多解释:

typedef std::function<bool(Item)> WHERE;//I was attempting to provide an explicit cast, 'auto' works fine in MSVS

Group where(WHERE func);//A simple "foreach boolean" search

使用上面的 - >

Groups::WHERE where = [](Item & x)-> bool{return x.has("NEW");};

结果是:

tst_groupstest.cpp:257:错误:从'GroupsTest :: groups():: __ lambda1'转换为非标量类型'Groups :: WHERE {aka std :: function}'请求Groups :: WHERE where = [](Item &x) - > bool {return x.has("NEW");};

我希望这是明显的,我找不到它.我计划通过这个项目支持Linux和Mac,所以我很想早点解决这个问题.

这是我当前的解决方法,如果可能的话,我宁愿远离这个(毕竟,我设计它的原因是考虑到lambdas的API就是拥有明显的简洁代码块).

本节编译(不使用lambdas)

struct lambdaCueListstdFunc{
    bool operator()(Groups::Item x)
    {
        return x.has("NEW");
    }
};

/**
 * Selects all cues for a particular list
 * @brief getCueList
 * @param list
 * @return a vector of all the cues for this list sorted by number.
 */
std::vector<Groups::Item> CueService::getCueList(std::string list)
{
    std::function<bool(Groups::Item)> where = lambdaCueListstdFunc();
//    auto where = [&list] (Groups::Item & x) ->
//    {
//        return x.get(la::cues::List) == list;
//    };
    std::vector<Groups::Item> result = cues()->where(where).sort(la::cues::NUMBER);
    return result; 

}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 5

您提供的函数签名std::function与您尝试分配给它的lambda 的函数签名不同.

typedef std::function<bool(Item)> WHERE; // <-- Takes argument by value

Groups::WHERE where = [](Item & x)-> bool{return x.has("NEW");};
//                           ^^^
// The lambda takes argument by reference
Run Code Online (Sandbox Code Playgroud)

更改任一个以匹配另一个,具体取决于您是否要通过值或引用传递.