我正在尝试lambda函数并创建一个跳转表来执行它们,但是我发现g++没有识别lambda函数的类型,因此我可以将它们分配给数组或元组容器。
其中一项尝试是:
auto x = [](){};
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };在编译过程中,我得到了以下错误:
tst.cpp:53:27: error: conversion from ‘main()::<lambda()>’ to non-scalar type ‘main()::<lambda()>’ requested
tst.cpp:54:39: error: conversion from ‘main()::<lambda()>’ to non-scalar type ‘main()::<lambda()>’ requested嗯,不能从A型转换为非标量型A型吗?这是什么意思?o.O
我可以使用std::function来使它工作,但问题是它似乎不适用于tuple:
function<void()> jmpTable[] = [](){}; // works
struct { int i; function<void()>> fn; } myTuple = {1, [](){}}; // works
tuple<int, function<void()>> stdTuple1 = {1, [](){}}; // fails
tuple<int, function<void()>> stdTuple2 = make_tuple(1, [](){}); // workstst.cpp:43:58: error: converting to ‘std::tuple<int, std::function<void()> >’ from initializer list would use explicit constructor ‘std::tuple<_T1, _T2>::tuple(_U1&&, _U2&&) [with _U1 = int, _U2 = main()::<lambda()>, _T1 = int, _T2 = std::function<void()>]’构造函数标记为显式?为什么?
所以我的问题是,我是在做一些无效的事情,还是这个版本不能很好地完成任务?
发布于 2013-05-25 08:10:09
嗯,不能从A型转换为非标量型A型吗?这是什么意思?o.O
不,那不是转换成相同的类型。尽管有相同的身体,不同的羔羊有不同的类型。GCC的新版本使这一点更加清晰,并给出了错误信息:
error: conversion from '__lambda1' to non-scalar type '__lambda0' requested更好的是:
error: no viable conversion from '<lambda at test.cc:2:18>' to 'decltype(x)' (aka '<lambda at test.cc:1:10>')我可以使用std::function来使它工作,但问题是它似乎不适用于tuple:
确实如此(至少我没有4.5.3需要测试),但是您的初始化并不完全正确。
tuple<int, function<void()>> stdTuple1 {1, [](){}}; // lose the = to initialise stdTuple1 directly发布于 2013-05-24 18:52:13
我不确定4.5.3中n3043的状态,但是您应该能够使用函数指针转换。如果我没有误解你的使用意图,这可能对你有用;
void (*x)();
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };https://stackoverflow.com/questions/16741486
复制相似问题