Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 726
dashesy Avatar asked Jun 22 '16 15:06

dashesy


People also ask

Is it possible to use unique_ptr in a class?

You can, of course, use std::unique_ptr as a composition member of your class. This way, you don’t have to worry about ensuring your class destructor deletes the dynamic memory, as the std::unique_ptr will be automatically destroyed when the class object is destroyed.

What is the size passed to static assert 2?

The size passed to it is ‘2’, which fails the condition to be checked, therefore producing the compile time error, and thus halting the compilation process. What are the advantages of static_assert over #error?

What is the message in static assert?

The message is a string of characters in the base character set of the compiler; that is, not multibyte or wide characters. The constant-expression parameter of a static_assert declaration represents a software assertion. A software assertion specifies a condition that you expect to be true at a particular point in your program.

What is static assertion in C++?

The C++ 11 standard introduced a feature named static_assert() which can be used to test a software assertion at the compile time. Syntax : static_assert( constant_expression, string_literal ); Parameters : constant_expression : An integral constant expression that can be converted to a Boolean.


2 Answers

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
{};
like image 87
Angew is no longer proud of SO Avatar answered Sep 18 '22 14:09

Angew is no longer proud of SO


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));
like image 34
Jarod42 Avatar answered Sep 17 '22 14:09

Jarod42