【发布时间】:2018-05-18 19:04:32
【问题描述】:
我正在试验 lambdas 以及不同的 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,即a 和b 当然是同一种类型而c 有不同的类型。
是否允许编译器让c 与a 属于同一类型?
我的意思是表达式是相同的,这将是一个明显的优化。
PS:如果捕获阻止了这种优化,那么没有捕获的 lambdas 呢?
相关:what is the type signature of a c++11/1y lambda function? 和 Can the 'type' of a lambda expression be expressed?
【问题讨论】:
标签: c++ optimization lambda language-lawyer