static_assert for unique_ptr of any type

烂漫一生 提交于 2021-02-07 13:46:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!