【问题标题】:How can I use templates to normalize number in range from 0 to 1?如何使用模板来规范化 0 到 1 范围内的数字?
【发布时间】:2014-04-10 15:28:51
【问题描述】:

我正在设计一个 RGB 颜色表示的类。 它具有三个属性:红色、绿色和蓝色。

到目前为止,我拥有 unsigned char int 类型的这 3 个属性(从 0 到 255)。我想使用 C++ 模板,所以我也可以使用其他类型,例如 floatdoubleint

但是,我需要知道最大值,这可能可以用 std::numeric_limits 解决。问题是浮点数。它们应该在 0..1 范围内。你有什么想法可以解决这个问题吗?

我的目标是能够将红色、绿色和蓝色从未知类型转换为数字 0..1。

【问题讨论】:

  • 带有 std::is_floating_point 的模板特化,只接受 0 到 1 之间的值作为 RGB 值。

标签: c++ templates


【解决方案1】:
template<class T>
RGBClass {
public:
    RGBClass():
        max_value(std::numberic_limits<T>::max())
        /* ... */
    {}
    /* ... */
    const T max_value;

private:
    T R_;
    T G_;
    T B_;
};

template<>
RGBClass<float> {
public: 
    RGBClass():
        max_value(1),
        /* ... */
    {}

    // convert other type to float 0..1
    template<class OTHER_TYPE>
    RGBClass(const OTHER_TYPE& other):
        max_value(1),
        R_((float)other.R_ / (float)other.max_value),
        /* ... */
    {}
    const float max_value;

private:
    float R_;
    float G_;
    float B_;
}

【讨论】:

    【解决方案2】:
    template<typename T, typename=void>
    struct pixel_component_range {
      static constexpr T max() { return std::numberic_limits<T>::max(); }
    };
    template<typename F>
    struct pixel_component_range<F, typename std::enable_if<std::is_floating_point<F>::value>::type>
    {
      static constexpr T max() { return 1.f; }
    };
    

    现在pixel_component_range&lt;T&gt;::max() 计算为整数的最大值,1. 计算浮点值。

    【讨论】:

      猜你喜欢
      • 2010-12-01
      • 2019-10-03
      • 2011-06-08
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 2018-11-29
      • 2020-07-19
      • 2020-03-31
      相关资源
      最近更新 更多