类在编译时隐式转换为整型(最好是bool)

Class implicit cast to integral type (preferably bool) at compiile-time

本文关键字:bool 整型 编译 转换      更新时间:2023-10-16

假设我们有一个整型值包装器。例如,像std::true_typestd::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>() )
//               ^^