Index: lib/Sema/SemaTemplateInstantiateDecl.cpp =================================================================== --- lib/Sema/SemaTemplateInstantiateDecl.cpp +++ lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -12,6 +12,7 @@ #include "clang/Sema/SemaInternal.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" +#include "clang/AST/ASTLambda.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclVisitor.h" @@ -3916,7 +3917,9 @@ ExprResult Init; { - ContextRAII SwitchContext(*this, Var->getDeclContext()); + ContextRAII SwitchContext( + *this, Var->getDeclContext(), + /*NewThisContext=*/!isLambdaCallOperator(getCurLexicalContext())); Init = SubstInitializer(OldVar->getInit(), TemplateArgs, OldVar->getInitStyle() == VarDecl::CallInit); } Index: test/SemaCXX/lambda-expressions.cpp =================================================================== --- test/SemaCXX/lambda-expressions.cpp +++ test/SemaCXX/lambda-expressions.cpp @@ -499,3 +499,15 @@ }; } } + +namespace PR27994 { +struct A { template A(T); }; + +template +struct B { + int x; + A a = [&] { int y = x; }; +}; + +B b; +}