C++语言学习(3): type 的概念

type 的概念

C++中的变量拥有类型, 这是显然的。

实际上,每个 object, 每个 reference, 每个 function, 每个 expression , 都有对应的 type (类型):

Each object, reference, function, expression in C++ is associated with a type, which may be fundamental, compound, or user-defined, complete or incomplete, etc.

type 的划分

type 可以分为:

  • fundamental type:void类型,空指针类型,数值类型(整数、浮点)
  • compound type:
    • union,class,array
    • enum,member pointer, pointer
    • function,reference
  • 用户自定义类型

在这里插入图片描述

类型判断 - fundamental

    constexpr bool q = std::is_fundamental<int>(); // true

我们直接查看 macosx14.4 (apple clang) 里的代码:
在这里插入图片描述
在这里插入图片描述
不妨展开 std::is_void<_Tp>::value 的实现, 发现是 is_same<T,U> 套壳,再往下是 _BoolConstant<T> 套壳,

template <class _Tp>
struct _LIBCPP_TEMPLATE_VIS is_void : public is_same<__remove_cv_t<_Tp>, void> {};

template <class _Tp, class _Up>
struct _LIBCPP_TEMPLATE_VIS is_same : _BoolConstant<__is_same(_Tp, _Up)> {};

template <bool _Val>
using _BoolConstant _LIBCPP_NODEBUG = integral_constant<bool, _Val>;

最终是到了 std::integral_constant<T, v>.

类型判断 - compound

    constexpr bool r = std::is_compound<int*>(); // true

在这里插入图片描述

std::integral_constant

可以看到 std::is_fundamental<T>std::is_compound<T> 都是基于 std::integral_constant<T, v> 的实现,但它并不复杂,它就是返回 static_cast<T>(v):

在这里插入图片描述

类型判断 - reference 和 function

constexpr bool s = std::is_function<void()>(); // true

首先,判断是否为 reference 是这样定义的:
在这里插入图片描述
其次,判断是否为 const 也是明确的:
在这里插入图片描述
然后,认为 std::is_reference<T>std::is_const<T> 之外的,都是 function:
在这里插入图片描述

总结

这一篇给出了C++中 type 的概念,包括 fundamental, compound 两种最基本的划分, 然后给出了 std::is_fundamental<T>, std::is_compound<T> 的 macos 代码,以及往下挖了2层、3层发现了 std::ingegral_constant 的使用等。

几个直观的例子如下:

    constexpr bool q = std::is_fundamental<int>();
    constexpr bool r = std::is_compound<int&>();
    constexpr bool s = std::is_function<void()>();
    constexpr bool t = std::is_literal_type<decltype("hell")>();

Refs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值