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

时间:2011-11-21 16:24:46

标签: c++ c++11

假设我有这样的功能:

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来获取下一个更大类型的表达式。

2 个答案:

答案 0 :(得分:7)

你必须为此自己专门设计模板:

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;

答案 1 :(得分:6)

Dani的回答有正确的想法,但重新发明轮子 我Boost.Integer是为了解决integer type selection的问题。

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

您不仅要避免使用新代码(以及新错误),还要使用最快类型进行所需的操作。如果速度不是你在Boost.Integer之后也可以选择最小的类型。