简体   繁体   English

获取 lambda 的 lambda 调用运算符的地址

[英]Getting address of a lambda call operator for a lambda that captures

Is it possible to get the address of the lambda call operator for a lambda having captures?是否可以获得具有捕获的 lambda 的 lambda 调用运算符的地址? And even more: to assign such a pointer to a common pointer which can point to different lambdas having the same captures and the same calling-parameters?甚至更多:将这样一个指针分配给一个公共指针,该指针可以指向具有相同捕获和相同调用参数的不同 lambda? Strictly speaking, assigning a result (class1::*)(... ) to another result (class2::*)(... ) shouldn't be directly possible, but you might do dirty tricks and cast the pointers which could be possible since the lambda-classes are notionally interchangeable.严格来说,将一个结果(class1::*)(... )分配给另一个结果(class2::*)(... )不应该是直接可能的,但是您可能会做一些肮脏的把戏并转换可能的指针是可能的,因为 lambda 类在概念上是可互换的。

So what's the "proper" syntax for this?那么这个“正确”的语法是什么? Even as a dirty trick.即使是一个肮脏的把戏。

The last line of the following code unfortunately doesn't work:不幸的是,以下代码的最后一行不起作用:

int main()
{
    int i;
    auto l100 = [&]()
    {
        i += 100;
    };
    using l100_t = decltype(l100);
    using l100_fn = void (l100_t::*)();
    l100_fn fn100 = &l100_t::operator ();
}

which can point to different lambdas having the same captures and the same calling-parameters它可以指向具有相同捕获和相同调用参数的不同 lambda

If you have some interface which expects the user to provide a "lambda" that "captures" a specific set of values, and takes a specific set of parameters, then it's not a lambda anymore.如果您有一些界面希望用户提供“捕获”一组特定值并采用一组特定参数的“lambda”,那么它不再是 lambda。 It's just a function pointer that is given a const& to a struct containing the "captured" values as one of its parameters.它只是一个 function 指针,它被赋予一个包含“捕获”值作为其参数之一的结构的const& After all, the receiving code needs to store the "captured" values, right?毕竟,接收代码需要存储“捕获”的值,对吧? So the user needs to provide a "capture" struct and a function pointer that takes the "capture" struct and the other arguments.因此,用户需要提供一个“捕获”结构和一个 function 指针,该指针采用“捕获”结构和另一个 arguments。

That's how you should build your API: clearly and explicitly.这就是你应该如何构建你的 API:清晰明确。 It's not the user's job to make sure they're capturing the right parameters;确保他们捕获正确的参数不是用户的工作。 it's the API's job to tell the user want values are being "captured", and the user provides a function pointer that interfaces with them. API 的工作是告诉用户想要的值被“捕获”,并且用户提供了一个与它们交互的 function 指针。

Yes, the user doesn't get to automatically treat those "captured" values as accessible by name;是的,用户不会自动将那些“捕获”的值视为可通过名称访问的; they have to use the parameter name to get at them.他们必须使用参数名称来获取它们。 But the API becomes a lot more coherent and a lot less fragile.但是 API 变得更加连贯且不那么脆弱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM