我正在设计一个 RGB 颜色表示的类。 它具有三个属性:红色、绿色和蓝色。
到现在为止,我拥有 unsigned char int 类型的这 3 个属性(从 0 到 255)。我想使用 C++ 模板,因此我也可以使用其他类型,例如 float、double 或 int。
但是,我需要知道最大值,这可能可以用 std::numeric_limits 来解决。问题是 float 。它们应该在 0..1 范围内。你有什么想法可以解决这个问题吗?
我的目标是能够将红色、绿色和蓝色从未知类型转换为数字 0..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_;
}
关于c++ - 如何使用模板规范化 0 到 1 范围内的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22992399/