在“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 ofIsClass<T>
exploits the property (and picksint
arbitrarily for typeX
)
我不明白的是为什么选择int
作为X
有效,即使我们测试 IsClass<>
结构 S
根本没有成员(它也适用于具有 int
以外成员的类类型)
最佳答案
简而言之,因为标准是这么说的。
根据 [dcl.mptr]/2 (我在这里只包括相关部分):
[ Example:
struct X { int a; }; struct Y; double X::* pmd; char Y::* pmc;
. . .
The declaration ofpmd
is well-formed even thoughX
has no members of typedouble
. Similarly, the declaration ofpmc
is well-formed even thoughY
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/