Implementing a traits class to check for incomplete types
authorMarcelo Juchem <marcelo@fb.com>
Wed, 3 Apr 2013 03:22:58 +0000 (20:22 -0700)
committerJordan DeLong <jdelong@fb.com>
Sun, 21 Apr 2013 20:20:54 +0000 (13:20 -0700)
Summary: A traits class to check for incomplete types

Test Plan: unit tests added

Reviewed By: delong.j@fb.com

FB internal diff: D760676

folly/Traits.h
folly/test/TraitsTest.cpp

index bc0a0bf68847f1270b389eb9a87d5a6b3ce2088e..ebdb84d1e28ac0ac2856fac14bdb3da18391795e 100644 (file)
@@ -277,6 +277,34 @@ struct IsOneOf<T, T1, Ts...> {
   enum { value = std::is_same<T, T1>::value || IsOneOf<T, Ts...>::value };
 };
 
+/**
+ * A traits class to check for incomplete types.
+ *
+ * Example:
+ *
+ *  struct FullyDeclared {}; // complete type
+ *  struct ForwardDeclared; // incomplete type
+ *
+ *  is_complete<int>::value // evaluates to true
+ *  is_complete<FullyDeclared>::value // evaluates to true
+ *  is_complete<ForwardDeclared>::value // evaluates to false
+ *
+ *  struct ForwardDeclared {}; // declared, at last
+ *
+ *  is_complete<ForwardDeclared>::value // now it evaluates to true
+ *
+ * @author: Marcelo Juchem <marcelo@fb.com>
+ */
+template <typename T>
+class is_complete {
+  template <unsigned long long> struct sfinae {};
+  template <typename U>
+  constexpr static bool test(sfinae<sizeof(U)>*) { return true; }
+  template <typename> constexpr static bool test(...) { return false; }
+public:
+  constexpr static bool value = test<T>(nullptr);
+};
+
 /*
  * Complementary type traits to check for a negative/non-positive value.
  *
index a2760ca8fa6718c97cdea20b14bea8041d753649..7a80c6cc7041d17cff799c0641be0d5b4221c64e 100644 (file)
@@ -96,6 +96,14 @@ TEST(Traits, is_negative) {
   EXPECT_FALSE(folly::is_non_positive(1u));
 }
 
+struct CompleteType {};
+struct IncompleteType;
+TEST(Traits, is_complete) {
+  EXPECT_TRUE((folly::is_complete<int>::value));
+  EXPECT_TRUE((folly::is_complete<CompleteType>::value));
+  EXPECT_FALSE((folly::is_complete<IncompleteType>::value));
+}
+
 int main(int argc, char ** argv) {
   testing::InitGoogleTest(&argc, argv);
   google::ParseCommandLineFlags(&argc, &argv, true);