我尝试检测一个类是否已在 C++ 中实现。该类要么仅在之前声明过(情况 1),要么已实现(情况 2)。为了检测类的实现,SFINAE 表达式应该评估sizeof(T)模板参数,如果类不完整,则模板参数将失败。
#include <type_traits>
// 1. Feature not supported: Class only declared
class Test;
// 2. Feature supported: Class implemented
// class Test {};
// Detection if class is complete
template<class T, class Enable = void>
struct is_complete
{
static constexpr bool value = false;
};
template<class T>
struct is_complete<T, std::enable_if_t<(sizeof(T) == sizeof(T))>>
{
static constexpr bool value = true;
};
int main(void)
{
if constexpr (is_complete<Test>::value)
{
// static_assert(is_complete<Test>::value, "Test is not complete"); …Run Code Online (Sandbox Code Playgroud)