[英]how to use the type of compile time constant primitive
如何使用编译时常量原语的类型作为其他变量的类型声明?
我正在尝试在c ++中为SI单位转换做一些模板元编程。 归结为如何在一个加号运算符之后自动确定我需要的原始精度。 例如:
template<typename Precision>
class Unit {
public:
Unit(Precision v) : value(v) {}
Precision value;
};
template<typename Precision1, typename Precision2>
struct PrecisionTransform {
constexpr static auto test = (Precision1)1 * (Precision2)1; // Compile time constant
using Type = Precision1; // TODO: ideally typeof(test)
};
template<typename Precision1, typename Precision2>
Unit<PrecisionTransform<Precision1, Precision2>::Type> operator+(const Unit<Precision1>& x, const Unit<Precision2>& y)
{
return Unit<PrecisionTransform<Precision1, Precision2>::Type>(x.value + y.value);
}
int main()
{
Unit<double> a = 2.0;
Unit<float> b = 1.0f;
auto c = a + b;
return 0;
}
或简单来说,会发生这种事吗?
float a = 1;
typeof(a) b = 2;
自从我走了这么远以来,这似乎很有可能。 但我不确定如何使用
差不多了 正如max66已经指出的那样,请使用decltype
。 首先,可以用以下类型的别名替换PrecisionTransform
类(为此,您必须#include <utility>
):
template <typename Precision1, typename Precision2>
using TransformType = decltype(std::declval<Precision1>() * std::declval<Precision2>());
std::declval<XYZ>()
只是(Precision1)1
一种更通用的表达方式,它允许您还使用没有可访问的构造函数的类型(在您的情况下不相关,因为您仅使用基元)。
然后,您的operator+
更改为:
template<typename Precision1, typename Precision2>
Unit<TransformType<Precision1, Precision2>> operator+(const Unit<Precision1>& x, const Unit<Precision2>& y)
{
return Unit<TransformType<Precision1, Precision2>>(x.value + y.value);
}
请注意,您在operator+
的版本中遇到了错字(两个操作数均使用Precision1
)。
如您在这里看到的,主要的编译器对此表示同意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.