其他分享
首页 > 其他分享> > lambdas在未评估的背景下(直到C 20)

lambdas在未评估的背景下(直到C 20)

作者:互联网

我目前正在阅读P0315R1篇论文,该论文在未评估的背景下谈论Lambda

文件中有一个声明解释了为什么lambdas不能出现在未评估的环境中(当然只有在C 20之前),如下所示:

Lambdas are a very powerful language feature, especially when it comes
to using higher-order algorithms with custom predicates or expressing
small, disposable pieces of code. Yet, they suffer from one important
limitation which cripples their usefulness for creative use cases;
they can’t appear in unevaluated contexts. This restriction was
originally designed to prevent lambdas from appearing in signatures,
which would have opened a can of worm for mangling because lambdas are
required to have unique types.

有人可以用一个例子解释这个陈述吗?

解决方法:

一点背景:链接器不理解函数重载 – 它们只能理解C语言中的函数名.这就是C编译器破坏你的函数名称的原因. void foo(int)变为_Z3fooi.受损的名称会对所有参数的类型进行编码.如果您的函数是由模板实例化生成的,那么所有模板参数也会被编码.如果它们本身就是模板类,则它们的模板参数将被递归编码,依此类推,直到达到像int或函数指针这样的基本类型.

Lambdas使这个具有挑战性,因为每个lambda都需要具有不同的类型.这对函数中定义的lambdas来说并不算太糟糕:

auto foo() { return [](){}; }
auto bar() { return [](){}; }

foo和bar返回不同的类型.如果你然后将它们传递给另一个函数模板,那么该模板的名称会被伪装成foo :: __ lambda1或其他类似的东西.

让lambdas出现在decltype中会破坏这种机制.

void bar(decltype([](){}));
void bar(decltype([](){})) {}

这是原型和定义吗?或者是这两种不同的超载条件?如何在翻译单元中识别它们(如何破坏名称)?

到现在为止,C禁止提出这个问题.你链接的论文给出了答案:这样的事情不能有联系.甚至不要试图破坏它们.

标签:c20,c,c11,lambda
来源: https://codeday.me/bug/20190827/1744742.html