C ++ 0x lambda,我如何作为参数传递? [英] C++0x lambda, how can I pass as a parameter?

查看:490
本文介绍了C ++ 0x lambda,我如何作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下C ++ 0x lambda相关代码:

Please look at the following C++0x lambda related code:

typedef uint64_t (*WEIGHT_FUNC)(void* param);
typedef std::map<std::string, WEIGHT_FUNC> CallbackTable;

CallbackTable table;
table["rand_weight"] = [](void* param) -> uint64_t
{
  return (rand() % 100 + 1);
};

我在Visual Studio 2010中遇到一个错误,lambda无法转换为类型 WEIGHT_FUNC 。我也知道答案:使用 std :: function object

I got an error (in Visual Studio 2010) that the lambda couldn't be converted to the type of WEIGHT_FUNC. I also know the answer: using std::function object:

typedef std::function<uint64_t (void*)>  WEIGHT_FUNC;

但是,我也想知道如何接收lambda WITHOUT类型 std :: function

However, I also want to know how I can receive the type of lambda WITHOUT using std::function. What type should it be?

推荐答案

对函数指针的转换是比较新的:它引入了 N3043

The conversion to function pointer is relatively new: It was introduced with N3043 on February 15, 2010.

虽然eg GCC 4.5实现它,Visual Studio 10于2010年4月12日发布,因此没有及时实现。正如James指出,此将在以后的版本中修复

While e.g. GCC 4.5 implements it, Visual Studio 10 was released on April 12, 2010 and thus just didn't implement it in time. As James pointed out, this will be fixed in future releases.

现在你必须使用这里提供的一个替代解决方案。

For the moment you have to use one of the alternative solutions provided here.

技术上类似下面的解决方法可以工作,但没有可变参数模板没有乐趣推广它(Boost.PP的救援...),没有安全网反对传递捕获lambdas:

Technically something like the following workaround would work, but without variadic templates its no fun to generalize it (Boost.PP to the rescue...) and there is no safety net against passing capturing lambdas in:

typedef uint64_t (*WeightFunc)(void* param);

template<class Func> WeightFunc make_function_pointer(Func& f) {
    return lambda_wrapper<Func>::get_function_pointer(f);
}

template<class F> class lambda_wrapper {
    static F* func_;
    static uint64_t func(void* p) { return (*func_)(p); }    
    friend WeightFunc make_function_pointer<>(F& f);    
    static WeightFunc get_function_pointer(F& f) {
        if (!func_) func_ = new F(f);
        return func;
    }
};

template<class F> F* lambda_wrapper<F>::func_ = 0;

// ...
WeightFunc fp = make_function_pointer([](void* param) -> uint64_t { return 0; });

这篇关于C ++ 0x lambda,我如何作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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