【问题标题】:C++98: Compile Time Detect floating point typeC++98:编译时检测浮点类型
【发布时间】:2023-04-09 04:28:01
【问题描述】:

因此,您可以使用以下代码在 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;

够简单...你可以为浮点做任何类似的事情吗(没有提升依赖项?)

【问题讨论】:

  • 为什么要在类声明之外初始化value常量?
  • @Constructor 我应该使用枚举,真的。但是因为初始化静态常量值的规则并不统一,所以每当我使用它时,我都会在类之外进行初始化以保持一致性。

标签: c++ templates c++98


【解决方案1】:

C++ standard* 声明:

应为每个基本类型提供专门化,包括浮点数和整数,包括布尔值。

(*- 我无法找到该标准的早期草案。如果有人可以在这里伸出援手,将不胜感激。)

由于std::numeric_limits 提供了is_integeris_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

【讨论】:

  • 你能评论一下为什么你的比 lenegds2k 更有效吗?
  • 它们在功能上是相同的,所以这真的取决于个人品味。我的方法以标准为中心:“标准说std::numeric_limits 专门用于整数和浮点值。它还定义了确定类型是专门类型还是整数类型的方法,隐含地赋予了确定类型是否为特定类型的能力是浮点类型。” @legends2k 的方法以数学为中心:“数字可以是整数或浮点数。两者都是有界的(在 C++ 中),因此如果类型不是整数,它必须是浮点数。”我会说使用哪个更直观。
  • @Lilshieste +1(回答和评论)总结:我的方法以标准为中心; legends2k 专注于数学
【解决方案2】:

由于只有三种浮点类型(根据 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 };
};

【讨论】:

  • 是的,我在 e atm 上使用了这个
【解决方案3】:

类似于您的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] = { };
}

【讨论】:

  • 你能评论一下为什么你的答案比 Lishieste 的答案更有效吗?
猜你喜欢
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
  • 2010-11-08
  • 1970-01-01
相关资源
最近更新 更多