2012-08-03 95 views
1
template <typename T, typename Y, typename... Args> 
class Bar 
{ 
    T& t; 
public: 
    Bar(T& t) : t(t) { } 
}; 

template <typename T, typename... Args> 
void Foo(T &function) { new Bar<T, void, Args...>(function); } 

int main() 
{ 
    auto foo = [] { }; 
    Foo(foo); // ok 

    Foo([] { }); // fails (tested on GCC 4.5.3) 
} 

为什么只有当lambda表达式作为Foo的参数内联写入lambda表达式时才会失败?内联lambda表达式导致编译器错误

回答

5
template <typename T, typename... Args> 
void Foo(T &function) { new Bar<T, void, Args...>(function); } 

Foo([] { }); // fails (tested on GCC 4.5.3) 

Lambda是临时的。不要尝试将临时引用绑定到引用。使用值,或const-reference或rvalue-reference。

+0

谢谢!海湾合作委员会的错误消息不是太有用。 – 2012-08-03 03:11:24