Hide destructor

I am implementing something very similar to std::vector , but using an array on the stack instead of allocating memory.

d-tor calls a function that uses SFINAE.

  • If value_type is a POD, the function has an empty body.
  • If value_type is a normal class, such a std::string , the function has a body and correctly destroys all the data.

Now I want to use this new std::vector as constexpr . However, even c-tor is declared constexpr , the code does not compile because the class has a nontrivial d-tor.

Here is a small piece of code:

 template<typename T, std::size_t SIZE> class SmallVector{ constexpr SmallVector() = default; ~SmallVector(){ destructAll_<value_type>(); } // ... template<typename X> typename std::enable_if<std::is_trivially_destructible<X>::value == true>::type destructAll_() noexcept{ } }; 

Is there anything I can do to make the class constexpr if value_type is a POD and retains functionality for data types other than POD.
(Not at the same time, of course)

+5
source share
1 answer

Unfortunately, there is no way to enable / disable the destructor using SFINAE or with future concepts. This is because destructos:

  • cannot be patterned
  • cannot have arguments
  • cannot have a return type

What you can do is specialize the whole class or, even better, create a base class that contains only construction / destruction and basic access and specializes in this.

 template <class T, class Enable = void> struct X { ~X() {} }; template <class T> struct X<T, std::enable_if_t<std::is_pod<T>::value>> { }; static_assert(std::is_trivially_destructible<X<int>>::value); static_assert(!std::is_trivially_destructible<X<std::vector<int>>>::value); 
+5
source

Source: https://habr.com/ru/post/1258364/


All Articles