c++ - 判断一个类型是否是类类型?

标签 c++ templates sfinae typetraits partial-specialization

在“C++ 模板 - 完整指南 - 第二版”一书的第 19.8.4 章中,作者展示了如何在编译时确定一个类型是否为类类型:

#include <iostream>
#include <type_traits>
using namespace std;

template <typename T, typename = void_t<>>
struct IsClass : false_type { };

template <typename T>
struct IsClass<T, void_t<int T::*>> : true_type { };

int main()
{
    struct S { };
    cout << IsClass<S>::value; // prints 1
}

本段说明偏特化如何检测类类型:

... only class types can be used as the basis of pointer-to-member types. That is, in a type construct of the form X Y::*, Y can only be a class type. The following formulation of IsClass<T> exploits the property (and picks int arbitrarily for type X)

我不明白的是为什么选择int作为X有效,即使我们测试 IsClass<>结构 S根本没有成员(它也适用于具有 int 以外成员的类类型)

最佳答案

简而言之,因为标准是这么说的。

根据 [dcl.mptr]/2 (我在这里只包括相关部分):

[ Example:

struct X {
  int a;
};
struct Y;

double X::* pmd;
char Y::* pmc;

. . .
The declaration of pmd is well-formed even though X has no members of type double. Similarly, the declaration of pmc is well-formed even though Y is an incomplete type.
. . .

基本上,只要已知类型 S 是类类型,构造 S::* 就是合式的。

所以你甚至可以这样:

int main()
{
    struct S;
    cout << IsClass<S>::value; // still prints 1
}

关于c++ - 判断一个类型是否是类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975536/

相关文章:

c++ - SFINAE:有些失败比其他失败更平等?

c++ - 使用哈希数组对罗密欧与朱丽叶文本进行统计分析。我差了 3684 个字中的 2 个字

C++ 大 vector 搜索项

c++ - 使用带有is_class <int>的std::conditional,获得编译错误

c++ - 引用水平第 2 部分

c++ - C++ 模板的部分特化 : template parameter not deducible

c++ - 使用 SFINAE 有选择地实例化模板的成员函数

c++ - Qt单元测试依赖问题

c++ - 在 C++ 中使用日期和时间

C++ sizeof 不适用于模板