Snippets

Federico Fuga Making POD Strong typed.

Created by Federico Fuga

File strongtype.hpp Added

  • Ignore whitespace
  • Hide word diff
+//
+// Created by Federico Fuga on 07/09/17.
+//
+
+#ifndef STRONGTYPE_H
+#define STRONGTYPE_H
+
+template <typename T, typename TAG>
+class strong_type {
+    T value;
+public:
+    using Base = T;
+    using Tag = TAG;
+
+    explicit strong_type (T v)
+    : value (v) {}
+
+    T get() const { return value; }
+};
+
+#endif //STRONGTYPE_H

File test_strongtype.cpp Added

  • Ignore whitespace
  • Hide word diff
+//
+// Created by Federico Fuga on 07/09/17.
+//
+
+#include <gtest/gtest.h>
+#include <strongtype.h>
+#include <type_traits>
+
+TEST(StrongType, usage)
+{
+    struct IdTag {};
+    using ID = strong_type<int,IdTag>;
+
+    ID i (10);
+
+    struct ValueTag {};
+    using Value = strong_type<ID::Base, ValueTag>;
+
+    Value j (10);
+
+    static_assert(!std::is_convertible<ID,Value>::value, "ID and values are convertible!");
+
+    ASSERT_EQ(i.get(), j.get());
+}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.