问题
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.
回答1:
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
{};
回答2:
You can create a trait for that:
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:
You can use this:
static_assert(std::is_same<decltype(expr),
std::unique_ptr<std::remove_pointer<decltype(expr.get())>::type>>::value, "");
Basically, what it does is creating a std::unique_ptr
out of the type from std::unique_ptr::get(), and comparing that to expr
. This will only ever be true if expr
is a std::unique_ptr
.
来源:https://stackoverflow.com/questions/37972394/static-assert-for-unique-ptr-of-any-type