如何使用编译时常量原语的类型
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
类替换为 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
)。
正如你在这里看到的,主要的编译器都同意这一点。
相关文章:
- 如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
- 出于什么目的,可能需要从Boost库中同步原语和容器
- 使用 c++11 的并发原语是否有一个体面的wait_any实现?
- 如何使用编译时常量原语的类型
- 从 JNI 中的原语获取数字的简单方法
- 如何在 Windows 上仅使用事件和联锁原语实现递归锁
- 库在C/C++和其他语言中重现Java原语hashCode逻辑
- 提升::精神(经典)原语与自定义解析器
- 如何从更基本的同步原语中创建多读/单写锁
- boost::asio:"strand"类型的同步原语有什么名称吗?
- Qt同步原语可以与非QThread线程一起使用吗
- std::vector<> 使用 resize() 派生,它不初始化原语和转发construct_back
- 数据结构的线程安全性,在哪里添加同步原语
- 我可以将哪些同步原语与克隆(2)(C/C++)一起使用
- 在使用jni时,如何清理jfloat等原语?
- 使用cgal创建参数化的3D原语
- 按值传递原语
- 将我转换的.obj文件转换为OpenGL原语
- 是否有可能在c++中为嵌入式平台创建一个新的原语类型?
- 重载大于操作符的操作符将用户定义类型强制转换为原语,信息丢失