gpt4 book ai didi

c++ - 假设相同的 lambda 表达式具有不同的类型是否安全?

转载 作者:可可西里 更新时间:2023-11-01 15:05:16 24 4
gpt4 key购买 nike

我正在试验 lambda 以及不同的 lambda 表达式具有不同类型的事实,即使它们是相同的。考虑这段代码

#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,即 ab 当然是同一类型,而 c 有不同的类型类型。

是否允许编译器让 ca 属于同一类型?

我的意思是表达式是相同的,这将是一个明显的优化。

PS:如果捕获阻止了这样的优化,那么没有捕获的 lambda 怎么办?

相关:what is the type signature of a c++11/1y lambda function?Can the 'type' of a lambda expression be expressed?

最佳答案

Is the compiler allowed to let c be of the same type than a?

没有。 [&counter](){counter++;} 是一个 lambda 表达式,根据 [expr.prim.lambda.closure]/1 :

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 表达式,即使它与前一个表达式相同,您也会得到一个唯一的类型。

您可以使用 typeid 来检查是否是这种情况:

#include <iostream>
#include <typeinfo>

template <typename T> void once(T t){
static bool first_call = true;
std::cout << typeid(t).name() << std::endl;
if (first_call) {
t();
}
first_call = false;
}

int main() {
int counter = 0;
auto a = [&counter](){counter++;};
once(a);
once(a);
std::cout << counter << std::endl; // 1

auto b = a; // same type
once(b);
std::cout << counter << std::endl; // 1

auto c = [&counter](){counter++;}; // different type
once(c);
once(c);
std::cout << counter << std::endl; // 2
}

结果:

Z4mainEUlvE_                                                                                                          
Z4mainEUlvE_
1
Z4mainEUlvE_
1
Z4mainEUlvE0_
Z4mainEUlvE0_
2

你可以看到有两个函数模板实例化。

关于c++ - 假设相同的 lambda 表达式具有不同的类型是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50417782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com