C++11模版元编程:如何判断一个类型是完整类型(complete type)

什么是完整类型(complete type)?
要明白这个概念不如先从不完整类型(incomplete type)开始.
简单说,如果在编译期编译器能计算出一个类型的size,那么它就是一个完整类型,否则就是不完整类型。

比如如下的向前声明,编译器遇到它时,并无法判断student这个类型有占用多大的空间,所以它就是一个不完整类型:

struct student *ps;

当编译器遇到student的定义时它就成了一个完整类型

struct student
{
    int num;
}                   /* student structure now completed */ 

实现

ok,现在我们搞明白了完整类型的概念,那么在C++11中如何判断 一个类型是完整类型呢?

只要对一个类型sizeof(T)能正确计算,这个T就是一个完整类型。

所以判断T是否为完整类型的模板函数就可以写成如下的样子:

// 根据SFINAE原则,sizeof(T)不能正确计算就进入此分支,value为false;
template <typename T, typename = void>
struct is_complete_type : std::false_type {};

// sizeof(T)能正确计算就进入此分支,value为true;
template <typename T>
struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};

调用示例

std::cout << "int is complete type: " << is_complete_type<int>::value << std::endl;
// output 1(true) for int
// 前向声明类型
struct other;
std::cout << "other is complete type: " << is_complete_type<other>::value << std::endl;
// output 0(false) for www forward declaration

参考资料:

《Incomplete Types》(https://docs.microsoft.com/en-us/cpp/c-language/incomplete-types?view=vs-2019)

《How to write is_complete template?》(https://stackoverflow.com/a/37193089/4116453)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值