gpt4 book ai didi

c++ - 为什么析构函数不能是模板?

转载 作者:太空狗 更新时间:2023-10-29 23:39:32 24 4
gpt4 key购买 nike

我不想在类似 union 类的类中使用 SFINAE 禁用用户声明的析构函数,就像通常在类中的构造函数那样:

#include <type_traits>
#include <cstdlib>

template< typename A, typename B >
struct U
{
constexpr U() = default;
constexpr U(A _a) : a(_a), s{false} {}
constexpr U(B _b) : b(_b), s{true} {}

union
{
A a;
B b;
};

bool s;

template< typename = std::enable_if_t< !(std::is_trivially_destructible< A >{} && std::is_trivially_destructible< B >{}) >, // disable if A and B is trivially destructible
bool is_noexcept = (noexcept(std::declval< A >().~A()) && noexcept(std::declval< B >().~B())) > // disable if A or B is not destructible
~U() noexcept(is_noexcept)
{
if (s) {
b.~B();
} else {
a.~A();
}
}
};

int main()
{
struct A {};
struct B {};
U< A, B > u;
static_assert(std::is_literal_type< A >{});
static_assert(std::is_literal_type< B >{}); // =>
static_assert(std::is_literal_type< U< A, B > >{});
return EXIT_SUCCESS;
}

但出现错误:

main.cpp:24:5: error: destructor cannot be declared as a template
~U() noexcept(is_noexcept)
^
1 error generated.
Failure!

在 C++ 中有这种限制的理论原因吗?或者它只是一个“遗产”?

最佳答案

任何类 U 都可以有一个且只有一个析构函数,该析构函数在该类中以名称 ~U() 声明并且完全不接受任何参数。

模板函数指定一个函数族,其中“族”描述包含一个或多个的集合,对成员数量没有上限。

这两个概念是互斥的。一个类不能同时具有恰好一个析构函数和一组析构函数。

关于c++ - 为什么析构函数不能是模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33868022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com