首页 > 解决方案 > 创建一个可以在类型和变量上调用的类型特征

问题描述

C++ 中有两个运算符可以在类型变量上调用:sizeoftypeid.

假设我们想用类似的行为实现我们自己的操作,比如*:

template<bool is_type>
struct type_traits_T;

template<>
struct type_traits_T<true> {
    template<typename T>
    struct type_traits {
        using mydecltype = T;
        // and other stuff...
    };
};

template<>
struct type_traits_T<false> {
    template<auto VAR>
    struct type_traits:
        type_traits_T<true>::type_traits<decltype(VAR)> {};
};

使用宏可以很好地工作:

#define type_traits(V) type_traits_T<is_type(V)>::type_traits<V>

上面缺少的部分是该is_type(V)部分。

有没有一种方法可以实现is_type(V)true如果是类型,如果是变量V,则为假?V如果没有,是否有办法通过静态反射提案实现这一目标?


*使用模板捕获变量有其自身的限制。它可以通过将对 decltype 的调用移动到宏中来重构。然而,问题并不集中在模板部分,这只是为了有一个简单可行的用例。

标签: c++reflectiontypetraits

解决方案


您可以使用函数模板:

template<typename>
constexpr bool is_type() {
    return true;
}

template<auto>
constexpr bool is_type() {
    return false;
}

#define type_traits(V) type_traits_T<is_type<V>()>::type_traits<V>

推荐阅读