【发布时间】:2015-06-21 12:26:17
【问题描述】:
基本上,我想实现一个float16 类型。但这个问题不是关于如何做到这一点的细节,而是关于如何设置,以便我的新 float16 类型与 float、double 和所有整数类型表现得恰当。
我希望我的float16 类型可以类似地转换为浮点数或双精度数。例如,它应该隐式转换为这两种类型。它还应该有 std::common_type (http://en.cppreference.com/w/cpp/types/common_type) 对其行为类似,因为它 std::common_types 对其他浮点类型的行为类似。这意味着std::common_type<my_float16, float>::type = float、std::common_type<my_float16, double>::type = double 和std::common_type<my_float16, T>::type = my_float16 其中T 是任何整数类型。
我需要编写哪些构造函数和强制转换运算符才能完成这项工作?任何帮助将不胜感激!
我的other recent question 可能是相关的。
编辑:好的,我已经像 Anton 那样构建了一个最小的示例。这是
struct float16 {
explicit operator int() {
return 0;
}
operator float() {
return 0.0f;
}
};
这对 float 和 float16 有正确的公共类型,但 int 和 float16 的公共类型仍然是 int。我不明白。
【问题讨论】:
-
试图回答你的问题,我发现了一个nice bug in GCC,它会让整个想法变得非常危险
-
请问为什么需要 16 位浮点数?这只是一个练习吗?
-
叫做半精度,在图形等方面有应用——见en.wikipedia.org/wiki/Half-precision_floating-point_format。我还想实现一个 float128 类型,同样的问题也适用。