首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++98:编译时检测浮点类型

C++98:编译时检测浮点类型
EN

Stack Overflow用户
提问于 2014-04-14 20:47:51
回答 3查看 767关注 0票数 2

因此,您可以使用以下内容在is_integral中制作一个假C++98:

代码语言:javascript
复制
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;

简单的enough...is

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-04-14 21:28:09

C++标准*声明:

每种基本类型,包括浮点数和整数,都应提供专门化。

(*如果有人能在这里伸出援手,我们将不胜感激。)

因为std::numeric_limitsis_integeris_specialized提供了定义,所以可以组合这些信息来推断类型是否是浮点类型。

例如:

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 2014-04-14 21:20:54

由于只有三种浮点类型( C++98§3.9.1/8),因此不难列举它们:

代码语言:javascript
复制
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 };
};
票数 1
EN

Stack Overflow用户

发布于 2014-04-14 21:29:09

类似于您的is_integral技巧的东西:

代码语言:javascript
复制
#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] = { };
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23070099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档