C ++ 11 lambdas到函数指针 [英] C++11 lambdas to Function Pointer

查看:154
本文介绍了C ++ 11 lambdas到函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用C ++ 11 lambdas开发应用程序,并需要将一些类型转换为函数指针。这在GCC 4.6.0中完美地工作:

I'm starting to develop applications using C++11 lambdas, and need to convert some types to function pointers. This works perfectly in GCC 4.6.0:

void (* test)() = []()
{
    puts("Test!");
};

test();

我的问题是当我需要在lambda中使用函数或方法局部变量:

My problem is when I need to use function or method local variables within the lambda:

const char * text = "test!";

void (* test)() = [&]()
{
    puts(text);
};

test();

G ++ 4.6.0会显示投放错误代码:

G++ 4.6.0 gives the cast error code:

main.cpp: In function 'void init(int)':
main.cpp:10:2: error: cannot convert 'main(int argc, char ** argv)::<lambda()>' to 'void (*)()' in initialization


$ b b

如果使用自动,它可以正常工作:

const char * text = "Test!";

auto test = [&]()
{
    puts(text);
};

test();

我的问题是:如何使用 [& ?在我的情况下,我不能使用STL std :: function (因为我的程序不使用C ++ RTTI和EXCEPTIONS运行时),它有一个简单的函数实现来解决这个问题? p>

My question is: how can I create a type for a lambda with [&]? In my case, I can not use the STL std::function (because my program does not use C++ RTTI and EXCEPTIONS runtime), and It has a simple implementation of function to solve this problem?

推荐答案


我不能使用STL std :: function(因为我的程序不使用C ++ RTTI和EXCEPTIONS runtime)

I can not use the STL std::function (because my program does not use C++ RTTI and EXCEPTIONS runtime)

然后您可能需要编写自己的 std :: function

Then you may need to write your own equivalent to std::function.

对于 std :: function ,类型擦除的通常实现不需要RTTI的功能;它通过常规的虚函数调用工作。所以写自己的版本是可行的。

The usual implementation of type erasure for std::function doesn't need RTTI for most of its functionality; it works through regular virtual function calls. So writing your own version is doable.

的确, std :: function 需要 RTTI是 target_type target 函数,这不是世界上最有用的函数。您可以使用 std :: function 而不调用这些函数,假设您使用的实现不需要RTTI的常规业务。

Indeed, the only things in std::function that need RTTI are the target_type and target functions, which are not the most useful functions in the world. You might be able to just use std::function without calling these functions, assuming that the implementation you're using doesn't need RTTI for its usual business.

通常,当您禁用异常处理时,程序会在遇到 throw 语句时关闭并抛出错误。因为大多数 std :: function 会发出的异常不是你能够恢复的那种异常(调用一个空的 function ,内存不足等),你可以使用 std :: function

Typically, when you disable exception handling, the program simply shuts down and errors out when encountering a throw statement. And since most of the exceptions that a std::function would emit aren't the kind of thing you would be able to recover from (calling an empty function, running out of memory, etc), you can probably just use std::function as is.

这篇关于C ++ 11 lambdas到函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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