makecontext参数#2的C ++ 0x lambda [英] C++0x lambda for makecontext argument #2

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

问题描述

我无法将C ++ 0x lambda函数作为第二个参数传递给 makecontext (来自ucontext.h)。 makecontext 的签名是:

I'm having trouble passing a C++0x lambda function as the second argument to makecontext (from ucontext.h). The signature of makecontext is:

void makecontext(ucontext_t*, void (*)(), int, ...);

以前,我可以应用C风格 )(void)) cast,到我使用的全局作用域函数。 A reinterpret_cast 会在C ++中做的。但是,对于C ++ 0x lambda函数,我得到以下错误:

Previously, I was able to apply a C-style (void (*)(void)) cast, to the global scope functions I used. A reinterpret_cast would do the trick in C++. However, with a C++0x lambda function, I get the following error:

error: invalid cast from type ‘main(int, char**)::<lambda(int)>’ to type ‘void (*)()’


b $ b

我使用G ++ 4.6。下面的代码足以产生编译错误:

I'm using G++ 4.6. The following code is sufficient to produce the compile error:

#include <ucontext.h>

void f1(int i) {}

int main(int argc, char *argv[]) {
  ucontext_t c;
  makecontext(&c, (void (*)(void))f1, 1, 123); // ok
  makecontext(&c, reinterpret_cast<void (*)(void)>(f1), 1, 123); // ok

  auto f2 = [](int i){};
  makecontext(&c, (void (*)(void))f2, 1, 123); // error
  makecontext(&c, reinterpret_cast<void (*) (void)>(f2), 1, 123); // error
  return 0;
}


推荐答案

[](int i){} 是一个无捕获的lambda,只有一个 int 参数,它可以隐式转换为 void(*)(int):指向一个函数的指针,它接受一个 int

[](int i){} is a captureless lambda that has a single int parameter and returns nothing; it is thus implicitly convertible to void(*)(int): a pointer to a function that takes a single int and returns nothing.

假设 makecontext 函数能够处理不同类型的函数它是,虽然文档有点模糊),那么你将需要使用两个casts使用一个lambda:一个将lambda转换为函数指针,一个将lambda转换为 void(*)() type:

Assuming the makecontext function is capable of handling functions with different types (it appears from its documentation that it is, though the documentation is a bit vague), then you'll need to use two casts to use it with a lambda: one to cast the lambda to a function pointer, and one to cast the lambda to the void(*)() type:

auto f2 = [](int i) { };
makecontext(&c, (void (*)(void))(void (*)(int))f2, 1, 123);

这是相当不安全的(在函数指针类型之间转换不是最安全的事情),所以最好将这种功能包装到实用程序库中。您可以用函数模板包装 makecontext 函数,以便确保您对函数的所有使用都是类型安全的,并且所有不安全的代码都封装在一个地方。

This is all rather unsafe (casting between function pointer types isn't exactly the safest thing to be doing), so it would be best to wrap this sort of functionality into a utility library. You can wrap the makecontext function with a function template so that you can be sure that all of your uses of the function are type safe, and all of the unsafe code is encapsulated in one place.

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

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