2012-07-10 76 views
6

考虑下面的代码:Lambda捕获导致不兼容的操作数类型错误?

main() 
{ 
    bool t; 
    ... 
    std::function<bool (bool)> f = t ? [](bool b) { return b; } : [](bool b) { return !b; }; // OK 
    std::function<bool (bool)> f = t ? [t](bool b) { return t == b; } : [t](bool b) { return t != b; }; // error 
} 

当铿锵3.1编译的,非捕获拉姆达的分配工作,而一个与捕获失败:

main.cpp:12:36: error: incompatible operand types ('<lambda at main.cpp:12:38>' and '<lambda at main.cpp:12:71>') 
     std::function<bool (bool)> f2 = t ? [t](bool b) { return t == b; } : [t](bool b) { return t != b; }; // error 
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

为什么捕捉相同的变量将导致2个lambda需要不兼容的类型?

回答

12

lambda的类型是“唯一的,非联合类类型”,称为闭包类型。每个lambda被实现为一个不同的类型,声明范围本地,它有一个重载的operator()来调用函数体。

:如果写:

auto a=[t](bool b){return t==b;}; 
auto b=[t](bool b){return t!=b;}; 

然后编译器编译此(或多或少):

class unique_lambda_name_1 
{ 
bool t; 
public: 
unique_lambda_name_1(bool t_) t(_t) {} 
bool operator() (bool b) const { return t==b; } 
} a(t); 
class unique_lambda_name_2 
{ 
bool t; 
public: 
unique_lambda_name_2(bool t_) t(_t) {} 
bool operator() (bool b) const { return t!=b; } 
} b(t); 

a和b具有不同的类型和不能使用在?:运算符中。

但是,§5.1.2(6)说,没有捕获的lambda的闭包类型有一个非显式的公共转换运算符,它将lambda转换为函数指针 - 可以实现非闭包作为简单的功能。任何具有相同参数和返回类型的lambda可以转换为相同类型的指针,因此三元?:运算符可以应用于它们。

实施例:非捕获拉姆达:

auto c=[](bool b){return b;}; 

被实现这样的:

class unique_lambda_name_3 
{ 
static bool body(bool b) { return b; } 
public: 
bool operator() (bool b) const { return body(b); } 
operator decltype(&body)() const { return &body; } 
} c; 

这意味着该行:

auto x = t?[](bool b){return b;}:[](bool b){return !b;}; 

实际上,这意味着:

// a typedef to make this more readable 
typedef bool (*pfun_t)(bool); 
pfun_t x = t?((pfun_t)[](bool b){return b;}):(pfun_t)([](bool b){return !b;}); 
+0

感谢您的详细解释。我不知道他们的实施方式不同。现在有道理。 – 2012-07-10 12:24:47