在Stack Overflow问题中,在C++ 11中不允许重新定义lambda,为什么?,给出了一个不编译的小程序:
int main() {
auto test = []{};
test = []{};
}
Run Code Online (Sandbox Code Playgroud)
问题得到了回答,一切似乎都很好.然后是Johannes Schaub并做了一个有趣的观察:
如果你
+在第一个lambda之前放置一个,它会神奇地开始工作.
所以我很好奇:为什么以下工作呢?
int main() {
auto test = +[]{}; // Note the unary operator + before the lambda
test = []{};
}
Run Code Online (Sandbox Code Playgroud)
假设我有一对相关的模板,我想自动将参数从一个函数转换为另一个函数.我怎样才能做到这一点?
template<int a> struct bar;
template<int a, int b> struct foo {
operator bar<a> const (); // operator-based conversion
};
template<int a> struct bar : public foo<a, a> {
bar() { }
template<int b> bar(const foo<a, b>&) { } // constructor-based conversion
};
template<int a, int b> foo<a, b>::operator bar<a> const () { return bar<a>(); }
template<int a> void f(bar<a> x, bar<a> y) { }
int main() {
bar<1> x;
foo<1, 2> y;
f(x, y);
}
Run Code Online (Sandbox Code Playgroud)
对此,gcc 4.8.3说:
template argument …Run Code Online (Sandbox Code Playgroud)