C++0x lambda, how can I pass as a parameter?

后端 未结 3 911
独厮守ぢ
独厮守ぢ 2020-12-10 12:02

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

typedef uint64_t (*WEIGHT_FUNC)(void* param);
typedef std::map Callba         


        
3条回答
  •  悲&欢浪女
    2020-12-10 12:22

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

    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.

    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 WeightFunc make_function_pointer(Func& f) {
        return lambda_wrapper::get_function_pointer(f);
    }
    
    template 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 F* lambda_wrapper::func_ = 0;
    
    // ...
    WeightFunc fp = make_function_pointer([](void* param) -> uint64_t { return 0; });
    

提交回复
热议问题