确定c++类是否具有私有析构函数

Determining whether a C++ class has a private destructor

本文关键字:析构函数 是否 c++ 确定      更新时间:2023-10-16

假设我有以下代码:

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");
}

是否可以实现上面的IsDestructorPrivate模板来确定类的析构函数是private还是protected ?

在我使用的情况下,我需要使用这个IsDestructorPrivate的唯一时间是在可以访问这样一个私有析构函数的地方,如果它存在的话。它不一定存在。允许IsDestructorPrivate是宏而不是模板(或者是解析为模板的宏)。

你可以像下面的例子那样使用std::is_destructible类型特征:

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

现场演示

如果T的析构函数为deletedprivatetrue,则

std::is_destructible<T>::value等于false