C++ 如何确定decltype表达式的较大类型

C++ 如何确定decltype表达式的较大类型,c++,c++11,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::in

假设我有这样一个函数:

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;
}
static const boost::int32_t SOME_const_VALUE=1073741823;
模板
targetType转换(sourceType源)
{
typedef decltype(源*某些常量值)MulType;
//typedef boost::int64\u t MulType\t;
MulType\u t val=(MulType\u t)源*(MulType\u t)某些常量值;
返回val/(MulType)某些常量值;
}
当我这样调用这个函数时

boost::int32_t i = std::numeric_limits<boost::int32_t>::max();
boost::int32_t k = Convert<boost::int32_t>(i);
boost::int32\u t i=std::numeric\u limits::max();
boost::int32_t k=转换(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;
}
模板
类{}
模板
班级更大
{
typedef boost::int16_t类型;
}
模板
班级更大
{
typedef boost::int32_t类型;
}
模板
班级更大
{
typedef boost::int64_t类型;
}
如果您不太喜欢键入以下内容,也可以创建宏:

#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);
#定义更大的(x,y)\
模板\
班级更大\
{ \
typedef boost::int##y###u t type\
}
较大(8,16);
较大(16,32);
更大(32,64);
然后像这样使用它

bigger<boost::int32_t>::type x;
biger::type x;

丹尼的答案有正确的想法,但重新发明了轮子。
是为了解决这个问题

static const boost::int32_t SOME_const_VALUE=1073741823;
模板
targetType转换(sourceType源)
{
typedef typename boost::int_t<8*sizeof(sourceType)+1>::fast MulType;
MulType\u t val=静态转换(源)*静态转换(某些常量值);
返回val/static(某些常量值);
}

您不仅可以避免新的代码(和新的bug),还可以使用最快的类型来完成所需的操作。如果速度不是Boost所追求的。Integer也可以选择最小的类型。

但这将是大量的样板代码,因为我必须为我使用的每种类型都这样做。我希望能有一种少键入的方法。@mkaes:可能有多少整数类型?他们都只是彼此的类型定义…这是真的。我使用boost::int8_t到int64_t,boost::uint8_8到uint64_t也是如此。那就是8个专业。@mkaes:我看不到8。。有8,16,32,64。@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);
}