【发布时间】:2020-09-25 13:18:54
【问题描述】:
C++ 中有两个运算符可以在types 和variables 上调用:sizeof 和typeid。
假设我们想用类似的行为实现我们自己的操作,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 的调用移动到宏中来重构。但是问题并不集中在模板部分,这里只是为了有一个简单可行的用例。
【问题讨论】:
-
您不能将类型传递给函数。如果
V是一种类型,则is_type_v<V>为true,否则为false,您可以接受吗? -
@NathanOliver 它显示了一个调用语法,该语法具有(错误?)解决方案可能是宏的概念。但是,是的,模板非常好,甚至是首选。
-
刚刚发现了这个quite similar question,令人兴奋的neat answer! 那里的解决方案可以在没有模板的情况下工作,因此它更通用,也可以处理不能作为模板参数的变量。
标签: c++ reflection typetraits