类在编译时隐式转换为整型(最好是bool)
Class implicit cast to integral type (preferably bool) at compiile-time
假设我们有一个整型值包装器。例如,像std::true_type
和std::false_type
这样的布尔包装器:
template<typename T , T VALUE>
struct integral_value_wrapper
{
static const T value = VALUE;
};
template<bool VALUE>
using boolean_wrapper = integral_value_wrapper<bool,VALUE>;
using true_wrapper = boolean_wrapper<true>;
using false_wrapper = boolean_wrapper<false>;
我们在自己的类中使用布尔包装器。例如,int检查器:
template<typename T>
struct is_int : public false_wrapper {};
template<>
struct is_int<int> : public true_wrapper {};
using type = int;
int main()
{
if( is_int<type>::value ) cout << "type is int" << endl;
}
我的问题是:是否有任何方法可以使类型(在这种情况下继承自bool包装器的类)隐式转换为整型值?
这允许我避免在布尔表达式中使用::value
成员,如下面的例子所示:
using type = int;
int main()
{
if( is_int<type> ) cout << "type is int" << endl; //How I can do that?
}
不能提供需要表达式的类型。但是如果在包装器中添加转换操作符,如下所示:
template<typename T , T VALUE>
struct integral_value_wrapper
{
static constexpr T value = VALUE;
constexpr operator T () const { return value; }
};
你可以这样写:
if ( is_int<type>() )
// ^^
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- JNI 日期值转换问题,在C++中获取不同的长整型值
- 将长整型值打印为带有前导零的十六进制
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 将整型常量映射到类型
- 将元组和整型实例合并到引用元组中
- 提升不良词法强制转换:将字符串转换为无符号长整型时,无法将源类型值解释为目标
- 为什么C++不允许两个同名的函数/类模板,区别仅在于非类型模板参数(整型)的类型?
- 将最小值整数转换为无符号长整型
- 如何将小端格式的QByteArray转换为无符号长整型
- 直接初始化无符号短整型的标准行为
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- 无符号和有符号短整型的位宽
- 将整型转换为浮点型时检测溢出
- 环礁和(长整型)的区别?
- 为什么允许将整型、枚举和指向成员的指针类型reinterpret_cast到自身?
- 将逗号格式化为长整型整数
- 类在编译时隐式转换为整型(最好是bool)