Determining if a C ++ class has a private destructor

Let's say I have the following code:

class Example { #ifndef PRIVATE_DESTRUCTOR public: #endif ~Example() { } public: friend class Friend; }; class Friend { public: void Member(); }; void Friend::Member() { std::printf("Example destructor is %s.\n", IsDestructorPrivate<Example>::value ? "private" : "public"); } 

Is it possible to implement the IsDestructorPrivate template above to determine if the destructor of the class is private or protected ?

In cases where I work, the only times when I need to use this IsDestructorPrivate are in places that have access to such a private destructor, if one exists. It does not necessarily exist. It is allowed that IsDestructorPrivate be a macro, not a template (or be a macro that allows the template). C ++ 11 is fine.

+6
source share
1 answer

You can use a line like std::is_destructible , as shown below:

 #include <iostream> #include <type_traits> class Foo { ~Foo() {} }; int main() { std::cout << std::boolalpha << std::is_destructible<Foo>::value << std::endl; } 

Live demo

std::is_destructible<T>::value will be false if the destructor T is deleted or private and true otherwise.

+10
source

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


All Articles