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

how to use the type of compile time constant primitive

本文关键字:原语 类型 常量 何使用 编译      更新时间:2023-10-16

如何使用编译时常量原语的类型作为其他变量的类型声明?

我正在尝试用 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类替换为 follwing 类型别名(您必须为此#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 )。

正如你在这里看到的,主要的编译器都同意这一点。