3

I was trying out lambda functions and making a jump table to execute them, but I found g++ didn't recognize the type of the lambda function such that I could assign them to an array or tuple container.

One such attempt was this:

auto x = [](){};
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };

On compilation I get these errors:

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

Hmmmm, can't convert from type A to non-scalar type A? What's that mean? o.O

I can use std::function to get this to work, but a problem with that is it doesn't seem to work with 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, [](){}); // works

 

tst.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()>]’

Constructor marked explicit? Why?

So my question is if I am doing something invalid or is this version just not quite up to the task?

4

2 回答 2

2

嗯,不能从类型 A 转换为非标量类型 A?那是什么意思?oO

不,这不是转换为同一类型。尽管具有相同的主体,但不同的 lambda 具有不同的类型。较新版本的 GCC 使这一点更清楚,并给出错误消息:

error: conversion from '__lambda1' to non-scalar type '__lambda0' requested

clang 做得更好:

error: no viable conversion from '<lambda at test.cc:2:18>' to 'decltype(x)' (aka '<lambda at test.cc:1:10>')

我可以使用 std::function 让它工作,但一个问题是它似乎不适用于元组:

确实如此(至少使用 4.5.4,我没有要测试的 4.5.3),但是您的初始化不太正确。

tuple<int, function<void()>> stdTuple1 {1, [](){}}; // lose the = to initialise stdTuple1 directly
于 2013-05-25T08:10:09.627 回答
0

我不确定 4.5.3 中n3043的状态,但你应该可以使用函数指针转换。如果我没有误解您的使用意图,这可能对您有用;

void (*x)();
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };
于 2013-05-24T18:52:13.043 回答