C++ 中有两个运算符可以在类型和变量上调用:sizeof和typeid.
假设我们想用类似的行为实现我们自己的操作,比如*:
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 的调用移动到宏中来重构。然而,问题并不集中在模板部分,这只是为了有一个简单可行的用例。