https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91428

            Bug ID: 91428
           Summary: Please warn on if constexpr
                    (std::is_constant_evaluated())
           Product: gcc
           Version: 9.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: barry.revzin at gmail dot com
  Target Milestone: ---

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?

Reply via email to