gpt4 book ai didi

c++ - 在编译时将类隐式转换为整数类型(最好是 bool)

转载 作者:太空狗 更新时间:2023-10-29 21:45:39 25 4
gpt4 key购买 nike

假设我们有一个整数值包装器。例如,像 std::true_typestd::false_type 这样的 bool 包装器:

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>;

我们将 bool 值包装器用于我们自己的类。例如,一个 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 包装器继承的类)隐式转换为整数值?

这使我可以避免在 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++ - 在编译时将类隐式转换为整数类型(最好是 bool),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17128447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com