可以表达lambda表达式的“类型”吗? [英] Can the 'type' of a lambda expression be expressed?

查看:184
本文介绍了可以表达lambda表达式的“类型”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将lambda表达式视为可调用对象的语法糖,可以表示未命名的底层类型?

Thinking of lambda expressions as 'syntactic sugar' for callable objects, can the unnamed underlying type be expressed?

例如:

struct gt {
    bool operator() (int l, int r) {
        return l > r;
    }
} ;

现在, [](int l,int r){return l> ; r; } 是上述代码的优雅替代(加上必要的gt的可调用对象的创建),但是有一种方法来表达gt(类型)本身?

Now, [](int l, int r) { return l > r; } is an elegant replacement for the above code (plus the necessary creation of callable objects of gt), but is there a way to express gt (the type) itself?

一个简单的用法:

std::set<int, gt> s1;  // A reversed-order std::set
// Is there a way to do the same using a lambda?
std::set<int, some-magic-here-maybe([](int l, int r) { return l > r; }) > s2;


推荐答案

不,你不能把它放入 decltype ,因为

No, you cannot put it into decltype because


lambda表达式不会出现在未求值的操作数中

A lambda-expression shall not appear in an unevaluated operand

您可以执行以下操作

auto n = [](int l, int r) { return l > r; };
std::set<int, decltype(n)> s(n);

但这真的很丑陋。请注意,每个lambda表达式都会创建一个新的唯一类型。如果之后您在其他地方执行以下操作, t 的类型不同于 s

But that is really ugly. Note that each lambda expression creates a new unique type. If afterwards you do the following somewhere else, t has a different type than s

auto n = [](int l, int r) { return l > r; };
std::set<int, decltype(n)> t(n);

您可以使用 std :: function ,但请注意,这将导致一小部分运行时成本,因为它需要间接调用lambda函数对象调用操作符。这在这里可能是可以忽略的,但是如果你想以这种方式传递函数对象到 std :: sort ,可能是很重要的。

You can use std::function here, but note that this will incur a tiny bit of runtime cost because it needs an indirect call to the lambda function object call operator. It's probably negligible here, but may be significant if you want to pass function objects this way to std::sort for example.

std::set<int, function<bool(int, int)>> s([](int l, int r) { return l > r; });

一如既往,首先编写档案:)

As always, first code then profile :)

这篇关于可以表达lambda表达式的“类型”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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