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

Aidan Goldfarb via cfe-commits cfe-commits at lists.llvm.org
Fri Jan 24 07:31:34 PST 2025


================
@@ -11714,13 +11714,49 @@ 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 {
+          if (TTPD->getTypeConstraint())
+            llvm_unreachable("ill-formed program");
+          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_a)
+              << 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_b)
+              << ParamD->getDeclName() << FirstArg << SecondArg
+              << NTTPD->getType();
+        }
+      } else if (auto *TTempPD = dyn_cast<TemplateTemplateParmDecl>(ParamD)) {
+        TTempPD->dump();
+        S.Diag(Templated->getLocation(),
+               diag::note_ovl_candidate_explicit_arg_mismatch_named)
+            << ParamD->getDeclName();
----------------
AidanGoldfarb wrote:

My initial thought was no, as we are casting a `NamedDecl` not a `TemplateParameter`. If the latter was case, one of the three casts would be guaranteed to succeed, but I am not sure if that is still the case with the former. 

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


More information about the cfe-commits mailing list