[llvm] cda0936 - Update coding standards for constexpr if statements; NFC

Aaron Ballman via llvm-commits llvm-commits at lists.llvm.org
Fri Aug 19 12:53:30 PDT 2022


Author: Aaron Ballman
Date: 2022-08-19T15:53:19-04:00
New Revision: cda093681bad901e64d0f6898d15121ab49cb074

URL: https://github.com/llvm/llvm-project/commit/cda093681bad901e64d0f6898d15121ab49cb074
DIFF: https://github.com/llvm/llvm-project/commit/cda093681bad901e64d0f6898d15121ab49cb074.diff

LOG: Update coding standards for constexpr if statements; NFC

We currently suggest that users not use an else clause after a return
statement in a prior if branch. e.g.,

if (foo)
  return 1;
else // Should remove this else clause
  return 10;

however, this suggestion is incorrect for a constexpr if statement
because one of the two branches will be a discarded statement and thus
can impact template instantiation behavior. This updates the coding
standard to make it clear that it's okay to have a return after an else
in a constexpr if statement.

I think this is an NFC change to the intent of the rule, which is why
I've not started an RFC for the changes.

Differential Revision: https://reviews.llvm.org/D132232

Added: 
    

Modified: 
    llvm/docs/CodingStandards.rst

Removed: 
    


################################################################################
diff  --git a/llvm/docs/CodingStandards.rst b/llvm/docs/CodingStandards.rst
index fd5bf25106b1..0f3059426701 100644
--- a/llvm/docs/CodingStandards.rst
+++ b/llvm/docs/CodingStandards.rst
@@ -1026,6 +1026,24 @@ Or better yet (in this case) as:
 The idea is to reduce indentation and the amount of code you have to keep track
 of when reading the code.
 
+Note: this advice does not apply to a ``constexpr if`` statement. The
+substatement of the ``else`` clause may be a discarded statement, so removing
+the ``else`` can cause unexpected template instantiations. Thus, the following
+example is correct:
+
+.. code-block:: c++
+
+  template<typename T>
+  static constexpr bool VarTempl = true;
+
+  template<typename T>
+  int func() {
+    if constexpr (VarTempl<T>)
+      return 1;
+    else
+      static_assert(!VarTempl<T>);
+  }
+
 Turn Predicate Loops into Predicate Functions
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 


        


More information about the llvm-commits mailing list