如何使用编译时常量原语类型

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 class 替换为以下类型别名(为此您必须 #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)。

如您所见here,主要编译器都同意这一点。