[clang] [Clang] Diagnose classes defined in the type of a variable template (PR #248352)

via cfe-commits cfe-commits at lists.llvm.org
Thu Dec 3 20:49:08 PST 2026


https://github.com/YzK0741 updated https://github.com/llvm/llvm-project/pull/248352

>From b4917aba9e9868ee9a77790865daf8c180722e30 Mon Sep 17 00:00:00 2001
From: YzK0741 <2353036486 at qq.com>
Date: Thu, 3 Dec 2026 08:19:48 +0800
Subject: [PATCH] [Clang] Diagnose classes defined in the type of a variable
 template

An unnamed class definition in a variable template declaration was treated as
the templated entity, so the parser passed the template parameters to the
class and Sema reported "cannot declare a class template with no name".

An unnamed class can never be a class template, so stop passing the template
parameters to ActOnTag for it.  Whether the template-head belongs to a
variable template is then decided at the closing brace: if a declarator
follows, Sema diagnoses the type definition, otherwise this is an anonymous
class template definition and the parser rejects it.

This also diagnoses a class defined in the result type of a function, as in
`template <int> struct {} f();`.

Fixes #82499
---
 clang/docs/ReleaseNotes.md                    |  4 +++
 .../clang/Basic/DiagnosticSemaKinds.td        |  2 ++
 clang/lib/Parse/ParseDeclCXX.cpp              | 27 +++++++++++++++++--
 clang/lib/Sema/SemaDecl.cpp                   |  8 ++++++
 clang/test/CXX/temp/p3.cpp                    | 18 +++++++++++++
 5 files changed, 57 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 9af260e7ff4769..604ea5d0252c37 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -955,6 +955,10 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
   unevaluated operand, such as glibc's `assert` in `decltype` at namespace
   scope.
 
+- Clang now diagnoses a class defined in the type of a variable template or in
+  the result type of a function, as in `template <int> constexpr struct {}
+  test;` and `template <int> struct {} f();`. (#GH82499)
+
 ### Improvements to Clang's time-trace
 
 ### Improvements to Coverage Mapping
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index df55b87a4394fb..c1316788ae486b 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2034,6 +2034,8 @@ def err_type_defined_in_param_type : Error<
   "%0 cannot be defined in a parameter type">;
 def err_type_defined_in_alias_template : Error<
   "%0 cannot be defined in a type alias template">;
+def err_type_defined_in_variable_template : Error<
+  "%0 cannot be defined in the type of a variable template">;
 def err_type_defined_in_condition : Error<
   "%0 cannot be defined in a condition">;
 def err_type_defined_in_enum : Error<
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 2d799e8e9585e0..272f8ceb6e7806 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -17,6 +17,7 @@
 #include "clang/Basic/Attributes.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Basic/DiagnosticParse.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/LiteralSupport.h"
@@ -2206,8 +2207,11 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
     // Don't pass down template parameter lists if this is just a tag
     // reference.  For example, we don't need the template parameters here:
     //   template <class T> class A *makeA(T t);
+    // An unnamed class cannot be a class template either.  If a declarator
+    // follows the class body, the template-head belongs to a variable template
+    // and Sema diagnoses the type definition.
     MultiTemplateParamsArg TParams;
-    if (TUK != TagUseKind::Reference && TemplateParams)
+    if (TUK != TagUseKind::Reference && TemplateParams && Name)
       TParams =
           MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
 
@@ -2300,11 +2304,30 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
   //   In a template-declaration which defines a class, no declarator
   //   is permitted.
   //
+  // An unnamed class cannot be a class template.  If a declarator follows, the
+  // class is the type of a variable template and Sema diagnoses the definition;
+  // if there is none, this is an anonymous class template definition.
+  bool AnonymousClassTemplate =
+      TUK == TagUseKind::Definition && !Name && !TemplateId &&
+      TemplateInfo.Kind == ParsedTemplateKind::Template;
+  bool HasFollowingDeclarator = Tok.isOneOf(
+      tok::identifier, tok::star, tok::amp, tok::ampamp, tok::l_paren,
+      tok::annot_cxxscope, tok::kw_const, tok::kw_volatile, tok::kw_restrict);
+  if (AnonymousClassTemplate && !HasFollowingDeclarator) {
+    if (TemplateInfo.TemplateParams && !TemplateInfo.TemplateParams->empty())
+      Diag(TemplateInfo.TemplateParams->front()->getTemplateLoc(),
+           diag::err_template_unnamed_class);
+    DS.SetTypeSpecError();
+    return;
+  }
+
   // After a type-specifier, we don't expect a semicolon. This only happens in
   // C, since definitions are not permitted in this context in C++.
   if (TUK == TagUseKind::Definition &&
+      !(AnonymousClassTemplate && HasFollowingDeclarator) &&
       (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
-      (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate || !isValidAfterTypeSpecifier(false))) {
+      (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate ||
+       !isValidAfterTypeSpecifier(false))) {
     if (Tok.isNot(tok::semi)) {
       const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
       ExpectAndConsume(tok::semi, diag::err_expected_after,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 9417c101084edf..6b75de0de4d942 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -8041,6 +8041,14 @@ NamedDecl *Sema::ActOnVariableDeclarator(
              "should have a 'template<>' for this decl");
     }
 
+    if ((IsVariableTemplate || IsVariableTemplateSpecialization) &&
+        D.getDeclSpec().hasTagDefinition()) {
+      TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
+      Diag(Tag->getLocation(), diag::err_type_defined_in_variable_template)
+          << Context.getCanonicalTagType(Tag);
+      Invalid = true;
+    }
+
     bool IsExplicitSpecialization =
         IsVariableTemplateSpecialization && !IsPartialSpecialization;
 
diff --git a/clang/test/CXX/temp/p3.cpp b/clang/test/CXX/temp/p3.cpp
index 9e561d0b9a83b2..4b8d33be4d8107 100644
--- a/clang/test/CXX/temp/p3.cpp
+++ b/clang/test/CXX/temp/p3.cpp
@@ -16,6 +16,24 @@ template<typename T> struct C { } // expected-error {{expected ';' after struct}
 
 A<int> c;
 
+namespace GH82499 {
+template <int>
+constexpr struct {} test; // expected-error {{cannot be defined in the type of a variable template}}
+
+template <int> struct {} *pointer; // expected-error {{cannot be defined in the type of a variable template}}
+
+template <int> struct {} array[3]; // expected-error {{cannot be defined in the type of a variable template}}
+
+template <int>
+struct {} const qualified{}; // expected-error {{cannot be defined in the type of a variable template}}
+
+using Next = int;
+template <int> struct MissingSemi {} // expected-error {{expected ';' after struct}}
+Next next;
+
+template <int> struct {}; // expected-error {{cannot declare a class template with no name}}
+}
+
 struct D {
   template<typename T> static const int x = 0, f(); // expected-error {{can only declare a single entity}}
 



More information about the cfe-commits mailing list