ARTICLE AD BOX
A colleague of mine showed me a program with explicit object parameter in a lambda function. The program is accepted by two compilers, but produces a strange result:
struct A { int a = 2; constexpr A(auto&&) {} }; constexpr int f() { return [i=1](this A){return i;}(); } int main() { return f(); // 2 in MSVC and EDG } static_assert( f() == 2 ); // true in EDG Both MSVC and EDG return 2 from main() despite seemingly expected 1 from [i=1](this A){return i;}();, EDG even evaluates this constant expression to 2, while MSVC complains:error C2131: expression did not evaluate to a constant note: failure was caused by attempting to access a member on an object of dynamic type 'A' in which the member is not defined
and GCC refuses to accept it at all:error: a lambda with captures may not have an explicit object parameter of an unrelated type
Could you please point out what is wrong with the program and which implementation is correct?
25k46 gold badges61 silver badges191 bronze badges
3
