0
点赞
收藏
分享

微信扫一扫

判断是否是函数类型(学习到了函数和引用没法被const修饰,重新复习了下顶层const和底层const)

陆公子521 2022-02-16 阅读 88
//是否是const类型利用特化是实现
template <class>
_INLINE_VAR constexpr bool is_const_v = false; // determine whether type argument is const qualified

template <class _Ty>
_INLINE_VAR constexpr bool is_const_v<const _Ty> = true;

template <class _Ty>
struct is_const : bool_constant<is_const_v<_Ty>> {};
//是否是volatile类型利用特化是实现
template <class>
_INLINE_VAR constexpr bool is_volatile_v = false; // determine whether type argument is volatile qualified

template <class _Ty>
_INLINE_VAR constexpr bool is_volatile_v<volatile _Ty> = true;

template <class _Ty>
struct is_volatile : bool_constant<is_volatile_v<_Ty>> {};
//是否是函数类型const没法修饰引用和函数类型,
//因此利用!is_const_v<const _Ty>获取是否可以被const修饰可以就返回true取反为false
//当没法被const修饰也不是引用,显然就是函数类型
template <class _Ty>
_INLINE_VAR constexpr bool is_function_v = // only function types and reference types can't be const qualified
    !is_const_v<const _Ty> && !is_reference_v<_Ty>;

template <class _Ty>
struct is_function : bool_constant<is_function_v<_Ty>> {};
//对象可以被const修饰,并且不是void类型
template <class _Ty>
_INLINE_VAR constexpr bool is_object_v = // only function types and reference types can't be const qualified
    is_const_v<const _Ty> && !is_void_v<_Ty>;

template <class _Ty>
struct is_object : bool_constant<is_object_v<_Ty>> {};

demo测试

#include <iostream>
#include <type_traits>
using namespace std;
namespace xxx
{
    template <class _Ty>
    _INLINE_VAR constexpr bool is_function_v = // only function types and reference types can't be const qualified
        !is_const_v<const _Ty>;
}
void const fun()
{

}
int main()
{
    
    int c = 10;
    int d = 1;
    int& b = c;
    constexpr bool a = xxx::is_function_v<decltype(b)>;
    constexpr bool j = xxx::is_function_v<decltype(fun)>;
    int* const f = &c;
    c = 20;
    int& const g = c;
}

在这里插入图片描述
在这里插入图片描述

举报

相关推荐

0 条评论