diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 219d73146ea3..3ee257a94eb5 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -616,6 +616,22 @@ Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, // whether this is a valid redeclaration. ClassTemplateDecl *PrevClassTemplate = dyn_cast_or_null(PrevDecl); + + // We may have found the injected-class-name of a class template, + // class template partial specialization, or class template specialization. + // In these cases, grab the template that is being defined or specialized. + if (!PrevClassTemplate && PrevDecl && isa(PrevDecl) && + cast(PrevDecl)->isInjectedClassName()) { + PrevDecl = cast(PrevDecl->getDeclContext()); + PrevClassTemplate + = cast(PrevDecl)->getDescribedClassTemplate(); + if (!PrevClassTemplate && isa(PrevDecl)) { + PrevClassTemplate + = cast(PrevDecl) + ->getSpecializedTemplate(); + } + } + if (PrevClassTemplate) { // Ensure that the template parameter lists are compatible. if (!TemplateParameterListsAreEqual(TemplateParams, diff --git a/clang/test/SemaTemplate/friend-template.cpp b/clang/test/SemaTemplate/friend-template.cpp index df27c920b7bc..9a483aeb5b1e 100644 --- a/clang/test/SemaTemplate/friend-template.cpp +++ b/clang/test/SemaTemplate/friend-template.cpp @@ -28,3 +28,19 @@ namespace N { template void f0(T) { } template void f1(T) { } // expected-error{{redefinition}} } + +// PR4768 +template +struct X0 { + template friend struct X0; +}; + +template +struct X0 { + template friend struct X0; +}; + +template<> +struct X0 { + template friend struct X0; +};