Search code examples
c++c++11destructorprivate

Determining whether 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's destructor is %s.\n",
        IsDestructorPrivate<Example>::value ? "private" : "public");
}

Is it possible to implement the IsDestructorPrivate template above to determine whether a class's destructor is private or protected?

In the cases I'm working with, the only times I need to use this IsDestructorPrivate are within places that have access to such a private destructor, if it exists. It doesn't necessarily exist. It is permissible for IsDestructorPrivate to be a macro rather than a template (or be a macro that resolves to a template). C++11 is fine.


Solution

  • You could use the std::is_destructible type trait like the example 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 equal to false if the destructor of T is deleted or private and true otherwise.