A very common user error with std::is_constant_evaluated is to write this: #include <type_traits> constexpr int foo(int i) { if constexpr (std::is_constant_evaluated()) { return 42; } else { return i; } } That is, check if we're in the middle of constant evaluation with "if constexpr" instead of plain "if". This is the intuitive check to do, but unfortunately, since the condition here is manifestly constant evaluated, the result of check is unconditionally true. gcc implements this correctly - the above function is exactly equivalent to "return 42;" - but that's unlikely to be what the user intended the program to do. They likely intended to write: constexpr int foo(int i) { if (std::is_constant_evaluated()) { return 42; } else { return i; } } Can you please provide a warning for this erroneous usage?
(In reply to Barry Revzin from comment #0) > Can you please provide a warning for this erroneous usage? Yes, I think this ought to me feasible to add to finish_if_stmt_cond.
*be
Author: mpolacek Date: Wed Aug 28 02:03:48 2019 New Revision: 274981 URL: https://gcc.gnu.org/viewcvs?rev=274981&root=gcc&view=rev Log: PR c++/91428 - warn about std::is_constant_evaluated in if constexpr. * cp-tree.h (decl_in_std_namespace_p): Declare. * semantics.c (is_std_constant_evaluated_p): New. (finish_if_stmt_cond): Warn about "std::is_constant_evaluated ()" in an if-constexpr. * typeck.c (decl_in_std_namespace_p): No longer static. * g++.dg/cpp2a/is-constant-evaluated9.C: New test. Added: trunk/gcc/testsuite/g++.dg/cpp2a/is-constant-evaluated9.C Modified: trunk/gcc/cp/ChangeLog trunk/gcc/cp/cp-tree.h trunk/gcc/cp/semantics.c trunk/gcc/cp/typeck.c trunk/gcc/testsuite/ChangeLog
Done in GCC 10.1.
Would it make sense to add a fixit hint that removes "constexpr"? I think that might make the warning a bit clearer for some users. On the other hand, if is_constant_evaluated gets removed by P1938, there is no point putting more work into it.
Well, but perhaps the right fix is removing "std::is_constant_evaluated ()" instead?