[clang] [clang][Sema] Improve template argument deduction diagnostic (PR #122754)

Aidan Goldfarb via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 22 12:01:49 PST 2025


================
@@ -11714,13 +11715,52 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
     return;
   }
 
-  case TemplateDeductionResult::InvalidExplicitArguments:
+  case TemplateDeductionResult::InvalidExplicitArguments: {
     assert(ParamD && "no parameter found for invalid explicit arguments");
-    if (ParamD->getDeclName())
-      S.Diag(Templated->getLocation(),
-             diag::note_ovl_candidate_explicit_arg_mismatch_named)
-          << ParamD->getDeclName();
-    else {
+    if (ParamD->getDeclName()) {
+      TemplateArgument FirstArg = *DeductionFailure.getFirstArg();
+      std::string ParamName = ParamD->getNameAsString();
+      TemplateArgument SecondArg = *DeductionFailure.getSecondArg();
+
+      if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(ParamD)) {
+        if (TTPD->wasDeclaredWithTypename())
+          S.Diag(Templated->getLocation(),
+                 diag::note_ovl_candidate_explicit_arg_mismatch_named_ttpd)
+              << ParamD->getDeclName() << FirstArg << SecondArg << ParamName
+              << "type";
+        else {
+          // TODO write tests for type constrained classes
+          if (auto *constraint = TTPD->getTypeConstraint())
+            S.Diag(Templated->getLocation(),
+                   diag::note_ovl_candidate_explicit_arg_mismatch_named_ttpd)
+                << ParamD->getDeclName() << FirstArg << SecondArg << ParamName
+                << "valid type-constrained class";
+          else
+            S.Diag(Templated->getLocation(),
+                   diag::note_ovl_candidate_explicit_arg_mismatch_named_ttpd)
+                << ParamD->getDeclName() << FirstArg << SecondArg << ParamName
+                << "class";
+        }
+      } else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) {
+        if (SecondArg.isNull()) {
+          // Expected constant of type 'int', got type 'int'
+          S.Diag(Templated->getLocation(),
+                 diag::note_ovl_candidate_explicit_arg_mismatch_named_nttpd_nsp)
+              << ParamD->getDeclName() << FirstArg << NTTPD->getType();
+        } else {
+          // Could not convert A from B to C
+          S.Diag(Templated->getLocation(),
+                 diag::note_ovl_candidate_explicit_arg_mismatch_named_nttpd_sp)
+              << ParamD->getDeclName() << FirstArg << SecondArg
+              << NTTPD->getType();
+        }
+      } else if (auto *TTempPD = dyn_cast<TemplateTemplateParmDecl>(ParamD)) {
----------------
AidanGoldfarb wrote:

Thank you for the suggestion. However, I am planning to at least attempt to make a better error message in this situation, so I would need this cast. 

https://github.com/llvm/llvm-project/pull/122754


More information about the cfe-commits mailing list