Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 904
Myria Avatar asked Aug 14 '14 20:08

Myria


1 Answers

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.

like image 110
101010 Avatar answered Sep 20 '22 01:09

101010