Search code examples
c++static-assert

static_assert for unique_ptr of any type


How can I statically assert that an expression is a std::unique_ptr i.e. std::unique_ptr<T> for any T.

static_assert (std::is_pointer<decltype(exp)>()), "not a smart pointer")

Above does not work. If nothing straight forward, I am only interested if bool() operator is defined for the type.


Solution

  • Create your own trait, with the appropriate partial specialisation:

    template <class T>
    struct is_unique_ptr : std::false_type
    {};
    
    template <class T, class D>
    struct is_unique_ptr<std::unique_ptr<T, D>> : std::true_type
    {};