在模板中区分整数和浮点类型 [英] Distinguishing integer from floating point types in a template

查看:28
本文介绍了在模板中区分整数和浮点类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对几种整数类型(16、32、64 位)和浮点类型(float、double、long double)执行类似但不相同的计算.大多数代码是相同的,但对于整数和浮点数,有些部分需要做不同的事情.例如,比较整数可以用 a==b 来完成,而比较浮点数应该用 abs(a-b) 来完成

一种方法是将整数和浮点数之间不同的代码部分隔离成小函数,并为每种类型专门化模板.但是,我不想为每个整数类型复制粘贴相同的代码,并为每个浮点类型复制粘贴另一个代码.因此问题是:是否可以同时为多种类型专门化模板函数?如果合法,则在语义上类似于以下内容:

I'd like to perform similar, but not identical computations for several integer types (16, 32, 64 bits) and floating point types (float, double, long double). Most of the code is identical, but some portions need to be done differently for ints and floats. For example, comparing ints can be done with a==b, while comparing floats should be done with abs(a-b)

One way to do that would be to isolate the parts of code that are different between ints and floats into small functions and specialize template for each type. However, I'd rather not to copy-paste identical code for each of the integer types and another code for each of the float types. Thus the question: is it possible to specialize template function for multiple types at once? Something semantically similar to the following if it was legal:

template<>
bool isEqual< short OR long OR long long >( T a, T b ) { 
    return a == b;
}

template<>
bool isEqual< float OR double OR long double >( T a, T b ) { 
    return abs( a - b ) < epsilon;
}

推荐答案

使用 C++11 可以使用 type特征.请参阅std::enable_if 文档在您的情况下,它可能如下所示:

With C++11 it is possible to use type traits. See std::enable_if documentation In your case, it might look like this:

函数参数特化:

template<class T>
bool isEqual(T a, T b, typename std::enable_if<std::is_integral<T>::value >::type* = 0) 
{
    return a == b;
}

template<class T>
bool isEqual(T a, T b, typename std::enable_if<std::is_floating_point<T>::value >::type* = 0) 
{
    return abs( a - b ) < epsilon;
}

返回类型特化:

template<class T>
typename std::enable_if<std::is_integral<T>::value, bool >::type isEqual(T a, T b)

{
    return a == b;
}

template<class T>
typename std::enable_if<std::is_floating_point<T>::value, bool >::type isEqual(T a, T b)
{
    return abs( a - b ) < epsilon;
}

这篇关于在模板中区分整数和浮点类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆