如何确定撤销类型表达式的更大类型

How to determine a larger type of a decltype expression

本文关键字:类型 表达式 何确定      更新时间:2023-10-16

假设我有这样一个函数:

static const boost::int32_t SOME_CONST_VALUE = 1073741823;
template<typename targetType, typename sourceType>
targetType Convert(sourceType source)
{
    typedef decltype(source * SOME_CONST_VALUE) MulType_t;
    //typedef boost::int64_t MulType_t;
    MulType_t val = (MulType_t)source * (MulType_t)SOME_CONST_VALUE;
    return val / (MulType_t)SOME_CONST_VALUE;
}

当我像这样调用这个函数

boost::int32_t i = std::numeric_limits<boost::int32_t>::max();
boost::int32_t k = Convert<boost::int32_t>(i);

k = 1,因为在乘法过程中溢出。将所有内容都转换为boost::int64_t将导致我想要的结果。但是我不想将short或char类型强制转换为int64类型的值。
那么我可以使用decltype来获得表达式的下一个更大的类型吗?

您必须为它创建自己的模板专门化:

template<typename tp>
class bigger { }
template
class bigger<boost::int8_t>
{
    typedef boost::int16_t type;
}
template
class bigger<boost::int16_t>
{
    typedef boost::int32_t type;
}
template
class bigger<boost::int32_t>
{
    typedef boost::int64_t type;
}

如果你不喜欢大量输入,你也可以创建一个宏:

#define BIGGER(x, y) 
    template 
    class bigger<boost::int##x##_t> 
    { 
        typedef boost::int##y##_t type; 
    }
BIGGER(8, 16);
BIGGER(16, 32);
BIGGER(32, 64);

然后像

一样使用
bigger<boost::int32_t>::type x;

Dani的答案有正确的想法,但重新做了一遍。
提振。整数是为了解决整数类型选择的问题。

static const boost::int32_t SOME_CONST_VALUE = 1073741823;
template<typename targetType, typename sourceType>
targetType Convert(sourceType source)
{
    typedef typename boost::int_t< 8 * sizeof( sourceType ) + 1 >::fast MulType_t;
    MulType_t val = static_cast<MulType_t>(source) * static_cast<MulType_t>(SOME_CONST_VALUE);
    return val / static_cast<MulType_t>(SOME_CONST_VALUE);
}

不仅避免了新的代码(和新的bug),而且您将使用最快的类型进行您想要的操作。如果速度不是你追求的,Boost。整数也可以选择最小类型

相关文章: