...

/

Multiple Destructors with C++20

Multiple Destructors with C++20

Get an overview of how multiple destructors are implemented with C++ 20.

We still have a class template, but instead of std::conditional, we use the trailing requires clause to provide an overload for the destructor.

Remember we learned earlier that, in class templates, we can provide function overloads using different constraints. This is true even for constructors and destructors.

Press + to interact
#include <iostream>
#include <string>
#include <type_traits>
template <typename T>
class Wrapper
{
T t;
public:
~Wrapper() requires (!std::is_trivially_destructible_v<T>) {
std::cout << "Not trivial\n";
}
~Wrapper() = default;
};
int main()
{
Wrapper<int> wrappedInt;
Wrapper<std::string> wrappedString;
}

In the example above, we first wrote a destructor with a requires clause on line 10. Then, we also provided the default implementation without specifying any constraint.

In the requires clause, we specify a constraint that makes it a valid overload only for types that are not trivially destructible. ...