请看下面的C++0x lambda相关代码:
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 Studio2010中),lambda无法转换为WEIGHT_FUNC类型。我也知道答案:使用std::function object
typedef std::function<uint64_t (void*)> WEIGHT_FUNC;但是,我也想知道如何在不使用std::function的情况下接收lambda类型。它应该是什么类型?
发布于 2010-07-24 03:45:36
到函数指针的转换相对较新:它是在2010年2月15日与N3043一起引入的。
例如,GCC 4.5实现了它,而Visual Studio10在2010年4月12日发布,因此没有及时实现。正如詹姆斯指出的那样,这个will be fixed在未来的版本中。
目前,您必须使用此处提供的替代解决方案之一。
从技术上讲,像下面这样的变通方法是可行的,但是如果没有可变模板,那么推广它就没有什么乐趣了(Boost.PP来拯救……)而且,在下面的代码中没有安全网来防止传递捕获lambdas:
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; });发布于 2010-07-24 03:09:21
如果你真的坚持不使用function<>,那么你可以使用decltype:
typedef decltype([](void*)->uint_64{return 0;}) my_lambda_type;我真的不推荐这样做,因为你对自己有很大的限制,我甚至不知道两个具有相同签名的lambda是否保证是同一类型。
发布于 2010-07-24 02:40:43
尝试(未测试):
#include <function>
typedef std::function< int64_t (void*) > weight_func;
typedef std::map<std::string, weight_func > CallbackTable;我认为除了使用std::function或等效函数之外,没有其他方法可以做到这一点。
https://stackoverflow.com/questions/3321283
复制相似问题