c++ - 创建一个可以在类型和变量上调用的类型特征
问题描述
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 的调用移动到宏中来重构。然而,问题并不集中在模板部分,这只是为了有一个简单可行的用例。
解决方案
您可以使用函数模板:
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>
推荐阅读
- mysql - 在间隔中选择最近的日期
- aframe - 如何触发框架的方向模式?
- reactjs - 如何让用户在登录后保持连接并让用户在 ReactJS 上注销
- c# - 如何在 Unity 运行时维护对对象实例化的引用
- excel - 使用公式复制整个表格列
- python - 如何将数据框列表从 R 导出到 Python?
- json - 尝试使用ansible中的键值对列表解析json输出
- api - 有没有办法取回在签名/完成后发送到 DocuSign 的原始未签名文档?
- python - 运行 Pika 的程序抛出 AMQPConnectionError
- python - 如何循环直到从文件中读取所有行?