创建一个可以在类型和变量上调用的类型特征

Create a type trait that can be called both on types and on variables

C++ 中有两个运算符可以在 typesvariables 上调用:sizeoftypeid.

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

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),如果 V 是一个类型,则结果是 true,如果 V 是一个变量,则结果是 false?如果没有,是否有办法通过 static reflection proposal?

来实现?

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

您可以使用函数模板:

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>