是否可以安全地假设相同的lambda表达式具有不同的类型? [英] Is it safe to assume that identical lambda expressions have different types?
问题描述
我正在尝试使用lambda和不同的lambda表达式具有不同类型的事实,即使它们是相同的.考虑一下这段代码
I am experimenting with lambdas and the fact that different lambda expressions have different types, even though they are the same. Consider this code
#include <iostream>
template <typename T> void once(T t){
static bool first_call = true;
if (first_call) t();
first_call = false;
}
int main() {
int counter = 0;
auto a = [&counter](){counter++;};
once(a);
once(a);
std::cout << counter; // 1
auto b = a; // same type
once(b);
std::cout << counter; // 1
auto c = [&counter](){counter++;}; // different type
once(c);
once(c);
std::cout << counter; // 2
}
此打印品112
,即a
和b
当然是相同的类型,而c
具有不同的类型.
This prints 112
, ie a
and b
are of course of same type and c
has a different type.
是否允许编译器使c
与a
具有相同的类型?
Is the compiler allowed to let c
be of the same type than a
?
我的意思是表达式是相同的,这将是显而易见的优化.
I mean the expressions are identical and it would be an obvious optimization.
PS:如果捕获阻止了这种优化,那么没有捕获的lambda呢?
PS: In case the capture prevents such an optimization, then what about lambdas without capture?
相关:什么是类型签名一个c ++ 11/1y lambda函数?和
推荐答案
是否允许编译器使
c
与a
具有相同的类型?
Is the compiler allowed to let
c
be of the same type thana
?
不. [&counter](){counter++;}
是lambda表达式,并且每个 [expr. prim.lambda.closure]/1 :
No. [&counter](){counter++;}
is a lambda expression and per [expr.prim.lambda.closure]/1:
lambda表达式的类型(也是闭包对象的类型)是一种唯一的,未命名的非工会类类型,称为闭包类型,其属性如下所述.
The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.
因此,对于每个lambda表达式,即使它与先前的表达式相同,您也将获得唯一的类型.
So, for each lambda expression, even if it is identical to a previous one, you will get a unique type.
这篇关于是否可以安全地假设相同的lambda表达式具有不同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!