C++98:编译时检测浮点类型
C++98: Compile Time Detect floating point type
因此,您可以在C++98中使用以下内容制作一个伪is_integral:
template <typename T>
struct is_integral
{
static const bool value;
};
template <typename T>
const bool is_integral<T>::value = std::numeric_limits<T>::is_integer;
很简单。。。对于浮点(不需要升压依赖性),你能做什么类似的事情吗?
C++标准*声明:
应为每种基本类型提供专业化,包括浮点和整数,包括布尔。
(*-我很难找到标准的早期草案。如果有人能在这里帮忙,我将不胜感激。)
由于std::numeric_limits
提供了is_integer
和is_specialized
的定义,因此可以结合这些信息来推断类型是否为浮点类型。
例如:
template <typename T>
struct is_floating_point
{
static const bool value;
};
template <typename T>
const bool is_floating_point<T>::value =
std::numeric_limits<T>::is_specialized && // Is fundamental arithmetic type...
!std::numeric_limits<T>::is_integer; // ...that is not an integer
由于只有三种浮点类型(根据C++98§3.9.1/8),因此不难枚举它们:
template <typename T>
struct is_floating_point {
enum { value = 0 };
};
template <>
struct is_floating_point<float> {
enum { value = 1 };
};
template <>
struct is_floating_point<double> {
enum { value = 1 };
};
template <>
struct is_floating_point<long double> {
enum { value = 1 };
};
类似is_integral
技巧的东西:
#include <limits>
#include <iostream>
template <typename T>
struct is_floating_point
{
static const bool value;
};
// is a fundamental type (i.e. not a user defined type) but not an integer
template <typename T>
const bool is_floating_point<T>::value =
!std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_bounded;
struct Obj
{
};
int main()
{
std::cout << is_floating_point<float>::value << std::endl; // 1
std::cout << is_floating_point<int>::value << std::endl; // 0
std::cout << is_floating_point<Obj>::value << std::endl; // 0
std::cout << is_floating_point<bool>::value << std::endl; // 0
std::cout << is_floating_point<double>::value << std::endl; // 1
std::cout << is_floating_point<long double>::value << std::endl; // 1
// this would compile since it's an array of size 1
int Y[is_floating_point<float>::value] = { };
// this wouldn't compile since it's an array of size 0
int N[is_floating_point<int>::value] = { };
}
相关文章:
- 如何检测 USRP USB 类型?
- 如何检测类型类型别名?
- 用于检测函数类型是否为否的特征
- 错误:在尝试检测 std::cout 是否<< t 时,功能强制转换为数组类型;有效
- 如何检测参数包中的uint8_t类型
- SFINAE - 检测类型 T 是指针、数组还是带有随机访问运算符的容器,以及给定的值类型
- 使用SFINAE来检测void返回类型函数的存在
- 如何为QImage检测足够的格式(数据类型)以消耗最少的RAM
- 有没有一种方法可以使用SFINAE来检测一个类型是否实现了给定的抽象基类
- C++模板可以检测特定类型的成员吗
- 检测习惯用语和默认参数类型匹配
- 使用"JSON for Modern C++"库检测整数不适合指定类型?
- SFINAE 检测是否定义了类型
- 检测类型是否为"mapping"
- 检测<T>某些非数字类型 T 的 std::numeric::type 的特化
- 类型检测:使用variadic参数正确实现计算平均值的函数
- 参数类型的编译时类型检测
- C++矩阵乘法类型检测
- 层次结构中的对象类型检测
- 泛型类型检测