Static_assert for unique_ptr of any type

How can I statically state that the expression is std::unique_ptr ie std::unique_ptr<T> for any T

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

Above does not work. If nothing is straightforward, I am only interested in the bool() operator for the type.

+5
source share
3 answers

Create your own characteristic with the corresponding partial specialization:

 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 {}; 
+6
source

You can create a trait for this:

 template <typename T, typename D> std::true_type is_unique_ptr_impl(const std::unique_ptr<T, D>&, int); template <typename T> std::false_type is_unique_ptr_impl(const T&, ...); template <typename T> using is_unique_ptr = decltype(is_unique_ptr_impl(std::declval<T>(), 0)); 
+3
source

You can use this:

 static_assert(std::is_same<decltype(expr), std::unique_ptr<std::remove_pointer<decltype(expr.get())>::type>>::value, ""); 

Basically, it creates std::unique_ptr from type std::unique_ptr::get() and compares this to expr . This will always be true if expr is std::unique_ptr .

+1
source

All Articles