Lambda 和 std::function

Lambdas and std::function(Lambda 和 std::function)
本文介绍了Lambda 和 std::function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在努力赶上 C++11 和所有很棒的新功能.我有点坚持 lambdas.

I'm trying to catch up on C++11 and all the great new features. I'm a bit stuck on lambdas.

这是我能够开始工作的代码:

Here's the code I was able to get to work:

#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <functional>

using namespace std;

template<typename BaseT, typename Func>
vector<BaseT> findMatches(vector<BaseT> search, Func func)
{
    vector<BaseT> tmp;

    for(auto item : search)
    {
        if( func(item) )
        {
            tmp.push_back(item);
        }
    }

    return tmp;
}

void Lambdas()
{
    vector<int> testv = { 1, 2, 3, 4, 5, 6, 7 };

    auto result = findMatches(testv, [] (const int &x) { return x % 2 == 0; });

    for(auto i : result)
    {
        cout << i << endl;
    }
}

int main(int argc, char* argv[])
{

    Lambdas();

    return EXIT_SUCCESS;
}

我想要的是这个:

template<typename BaseT>
vector<BaseT> findMatches(vector<BaseT> search, function <bool (const BaseT &)> func)
{
    vector<BaseT> tmp;

    for(auto item : search)
    {
        if( func(item) )
        {
            tmp.push_back(item);
        }
    }

    return tmp;
}

基本上我想将可能的 lambdas 缩小到一个合理的函数子集.我错过了什么?这甚至可能吗?我使用的是 GCC/G++ 4.6.

Basically I want to narrow down the possible lambdas to a sensible subset of functions. What am I missing? Is this even possible? I'm using GCC/G++ 4.6.

推荐答案

Stephan T. Lavavej 解释了为什么这在 这个视频.基本上,问题在于编译器试图从 both std::vector 推导出 BaseTcode>std::function 参数.C++ 中的 lambda 不是 std::function 类型,它是一种未命名的、唯一的非联合类型,如果它没有捕获列表(空 []).另一方面,可以从任何可能类型的可调用实体(函数指针、成员函数指针、函数对象)创建 std::function 对象.

Stephan T. Lavavej explains why this doesn't work in this video. Basically, the problem is that the compiler tries to deduce BaseT from both the std::vector and the std::function parameter. A lambda in C++ is not of type std::function, it's an unnamed, unique non-union type that is convertible to a function pointer if it doesn't have a capture list (empty []). On the other hand, a std::function object can be created from any possible type of callable entity (function pointers, member function pointers, function objects).

请注意,我个人不明白为什么您要将传入的函子限制为该特定签名(除了通过多态函数包装器间接进行的事实之外,例如 std::function, 远比直接调用函子(甚至可能被内联)低效),但这是一个工作版本.基本上,它禁用了 std::function 部分的参数推导,并且只从 std::vector 参数推导了 BaseT:

Note that I personally don't understand why you would want to limit the incoming functors to that specific signature (in addition to the fact that indirection through a polymorphic function wrapper, like std::function, is by far more inefficient than a direct call to a functor (which may even be inlined)), but here's a working version. Basically, it disables argument deduction on the std::function part, and only deduces BaseT from the std::vector argument:

template<class T>
struct Identity{
  typedef T type;
};

template<typename BaseT>
vector<BaseT> findMatches(vector<BaseT> search, 
    typename Identity<function<bool (const BaseT &)>>::type func)
{
    vector<BaseT> tmp;

    for(auto item : search)
    {
        if( func(item) )
        {
            tmp.push_back(item);
        }
    }

    return tmp;
}

Ideone 上的实例.

另一种可能的方法是不直接限制函子类型,而是通过 SFINAE 间接限制:

Another possible way would be to not restrict the functor type directly, but indirectly through SFINAE:

template<class T, class F>
auto f(std::vector<T> v, F fun)
    -> decltype(bool(fun(v[0])), void())
{
  // ...
}

Ideone 上的实例.

如果 fun 不接受 T& 类型的参数或者返回类型不能转换为 ,这个函数将从重载集中删除布尔., void() 使得 f 的返回类型为 void.

This function will be removed from the overload set if fun doesn't take an argument of type T& or if the return type is not convertible to bool. The , void() makes f's return type void.

这篇关于Lambda 和 std::function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)