[llvm-dev] RFC: Strong typedef for LLVM

Nevin Liber via llvm-dev llvm-dev at lists.llvm.org
Thu Aug 1 14:50:03 PDT 2019


On Thu, Aug 1, 2019 at 10:57 AM David Greene via llvm-dev <
llvm-dev at lists.llvm.org> wrote:

>   template<typename Tag, typename T>
>   class StrongTypedef {
>   public:
>     using BaseType = T;
>
>   private:
>     BaseType Value;
>
>   public:
>     constexpr StrongTypedef() : Value() {}
>     constexpr StrongTypedef(const StrongTypedef<Tag, T> &) = default;
>     explicit constexpr StrongTypedef(const BaseType &V) : Value(V) {}
>     explicit StrongTypedef(BaseType &&V)
>         noexcept(std::is_nothrow_move_constructible<BaseType>::value) :
>         Value(std::move(V)) {}
>
>   public:
>     explicit operator BaseType&() noexcept {
>       return Value;
>     }
>
>     explicit operator const BaseType&() const noexcept {
>       return Value;
>     }
>
>     friend void swap(StrongTypedef &A, StrongTypedef &B) noexcept {
>       using std::swap;
>       swap(static_cast<BaseType&>(A), static_cast<BaseType&>(B));
>     }
>   };
>

I'm generally a fan of using the type system to encapsulate this kind of
thing.  A few points:

   - Why no move assignment operator?
   - swap has the wrong noexcept specification.
   - In my experience, most of these types end up being equality comparable
   and hashable.  I understand that equality comparison is separate concern
   which can be provided by mixins, but the more boilerplate that is required
   to use it, the less likely people are to adopt it.  This could, of course,
   be constrained on whether or not the BaseType supports these operations.
   - Similar argument about using CRTP, as it requires more boilerplate
   (the using StrongTypedef::StrongTypedef; statement to bring in the
   converting constructor).
   - Not a fan of the name StrongTypedef (or OpaqueTypedef) either.  If the
   C++ standard ever acquires related functionality, there will end up being a
   conceptual mismatch.

-- 
 Nevin ":-)" Liber  <mailto:nevin at cplusplusguy.com <nevin at eviloverlord.com>>
+1-847-691-1404
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20190801/be2d5aa6/attachment.html>


More information about the llvm-dev mailing list