直到C+20
Unfortunately, there is no way to enable/disable destructor with SFINAE, nor with future concepts. That is because destructos:
您可以做的是专门化整个类,或者更好的是,创建一个仅包含构造/析构和基本访问的基类并将其专门化。
template <class T, class Enable = void>
struct X {
~X() {}
};
template <class T>
struct X<T, std::enable_if_t<std::is_pod<T>::value>> {
};
static_assert(std::is_trivially_destructible<X<int>>::value);
static_assert(!std::is_trivially_destructible<X<std::vector<int>>>::value);
C++ 20
据我所知,您可以约束析构函数并通过一个非常简单而优雅的解决方案获得您想要的结果:
template<typename T, std::size_t SIZE>
class SmallVector{
public:
constexpr SmallVector() = default;
~SmallVector() requires std::is_trivially_destructible_v<T> = default;
~SmallVector()
{
}
};
static_assert(std::is_trivially_destructible_v<SmallVector<int, 4>>);
static_assert(!std::is_trivially_destructible_v<SmallVector<std::string, 4>>);
然而,这是一个全新的功能,最近发生了一些变化(例如,参见禁用带有概念的非模板方法 https://stackoverflow.com/questions/58381851/disable-non-templated-methods-with-concepts)并且编译器支持仍然很粗略。 gcc 编译得很好,而 clang 因析构函数有两个定义而感到困惑godbolt https://godbolt.org/z/m744W6