编写一个接受lambda表达式作为参数的函数 [英] Write a function that accepts a lambda expression as argument

查看:828
本文介绍了编写一个接受lambda表达式作为参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的方法

template<typename T, typename U>
map<T,U> mapMapValues(map<T,U> old, T (f)(T,U))
{
    map<T,U> new;
    for(auto it = old.begin(); it != old.end(); ++it)
    {
        new[it->first] = f(it->first,it->second);
    }
    return new; 
}

并且想法是这样调用

BOOST_AUTO_TEST_CASE(MapMapValues_basic)
{
    map<int,int> test;
    test[1] = 1;
    map<int,int> transformedMap = VlcFunctional::mapMapValues(test, 
        [&](int key, int value) -> int
        {
            return key + 1; 
        }
    );
}

但是我得到错误:没有函数模板的实例VlcFunctional :: mapMapValues 匹配参数列表参数类型是:(std :: map,std :: allocator >>,__lambda1)

However I get the error: no instance of function template "VlcFunctional::mapMapValues" matches the argument list argument types are: (std::map, std::allocator>>, __lambda1)

任何想法我做错了什么? Visual Studio 2008和Intel C ++编译器11.1

Any idea what I'm doing wrong? Visual Studio 2008 and Intel C++ compiler 11.1

推荐答案

您的函数需要一个函数指针,而不是lambda。

Your function is expecting a function pointer, not a lambda.

在C ++中,通常有3种类型的可调用对象。

In C++, there are, in general, 3 types of "callable objects".


  1. 指针。

  2. 函数对象。

  3. Lambda函数。

如果你想在你的函数接口中使用所有这些,你可以使用 std :: function

If you want to be able to use all of these in your function interface, then you could use std::function:

template<typename T, typename U> 
map<T,U> mapMapValues(map<T,U> old, std::function<T(T, U)> f)
{
    ...
}

这将允许使用上述三种类型的可调用对象中的任何一种来调用函数。然而,这种方便的价格是对函数调用的小量开销(通常是空指针检查,然后是通过函数指针的调用)。这意味着该函数几乎肯定不是内联函数(除非有高级 WPO / LTO )。

This will allow the function to be called using any of the three types of callable objects above. However, the price for this convenience is a small amount of overhead on invokations on the function (usually a null pointer check, then a call through a function pointer). This means that the function is almost certainly not inlined (except maybe with advanced WPO/LTO).

或者,您可以添加一个附加模板参数,以采用任意类型第二个参数。这将更有效,但你失去对所使用的函数的类型安全,并可能导致更多的代码膨胀。

Alternatively, you could add an additional template parameter to take an arbitrary type for the second parameter. This will be more efficient, but you lose type-safety on the function used, and could lead to more code bloat.

template<typename T, typename U, typename F> 
map<T,U> mapMapValues(map<T,U> old, F f) 

这篇关于编写一个接受lambda表达式作为参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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