[llvm-commits] [llvm] r91123 - /llvm/trunk/include/llvm/ADT/StringSwitch.h

Gabor Greif ggreif at gmail.com
Fri Dec 11 07:30:07 PST 2009


Author: ggreif
Date: Fri Dec 11 09:30:07 2009
New Revision: 91123

URL: http://llvm.org/viewvc/llvm-project?rev=91123&view=rev
Log:
Simplify this class by removing the result cache.

This change removes the DefaultConstructible
and CopyAssignable constraints on the template
parameter T (the first one).

The second template parameter (R) is defaulted to be
identical to the first and controls the result type.
By specifying it to be (const T&) additionally the
CopyConstructible constraint on T can be removed.

This allows to use StringSwitch e.g. for llvm::Constant
instances.

Regarding the other review feedback regarding performance
because of taking pointers, this class should be completely
optimizable like before, since all methods are inline and
the pointer dereferencing and result value caching should be
possible behind the scenes by the "as-if" rule.

Modified:
    llvm/trunk/include/llvm/ADT/StringSwitch.h

Modified: llvm/trunk/include/llvm/ADT/StringSwitch.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/StringSwitch.h?rev=91123&r1=91122&r2=91123&view=diff

==============================================================================
--- llvm/trunk/include/llvm/ADT/StringSwitch.h (original)
+++ llvm/trunk/include/llvm/ADT/StringSwitch.h Fri Dec 11 09:30:07 2009
@@ -38,28 +38,24 @@
 ///   .Cases("violet", "purple", Violet)
 ///   .Default(UnknownColor);
 /// \endcode
-template<typename T>
+template<typename T, typename R = T>
 class StringSwitch {
   /// \brief The string we are matching.
   StringRef Str;
 
-  /// \brief The result of this switch statement, once known.
-  T Result;
-
-  /// \brief Set true when the result of this switch is already known; in this
-  /// case, Result is valid.
-  bool ResultKnown;
+  /// \brief The pointer to the result of this switch statement, once known,
+  /// null before that.
+  const T *Result;
 
 public:
   explicit StringSwitch(StringRef Str)
-  : Str(Str), ResultKnown(false) { }
+  : Str(Str), Result(0) { }
 
   template<unsigned N>
   StringSwitch& Case(const char (&S)[N], const T& Value) {
-    if (!ResultKnown && N-1 == Str.size() &&
+    if (!Result && N-1 == Str.size() &&
         (std::memcmp(S, Str.data(), N-1) == 0)) {
-      Result = Value;
-      ResultKnown = true;
+      Result = &Value;
     }
 
     return *this;
@@ -92,16 +88,16 @@
       .Case(S4, Value);
   }
 
-  T Default(const T& Value) {
-    if (ResultKnown)
-      return Result;
+  R Default(const T& Value) const {
+    if (Result)
+      return *Result;
 
     return Value;
   }
 
-  operator T() {
-    assert(ResultKnown && "Fell off the end of a string-switch");
-    return Result;
+  operator R() const {
+    assert(Result && "Fell off the end of a string-switch");
+    return *Result;
   }
 };
 





More information about the llvm-commits mailing list