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.
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.
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?
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.
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.
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
{};
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With