[英]compile-time conversions of floating point constants
This question refers to my previous question: float conversions in templates 这个问题涉及我以前的问题: 模板中的浮点转换
I would like to prevent a run-time conversion of floating-point constants. 我想防止浮点常量的运行时转换。 The prevailing view taken in my previous question was, that, say, a
float(.5)
conversion is allowed to take place at run-time. 我在上一个问题中所采用的普遍观点是,例如,在运行时允许进行
float(.5)
转换。 But how about: 但是如何:
template <typename A, typename B>
constexpr A convert(B const a)
{
return a;
}
An assert to guarantee the compile-time evaluation of a constexpr
function is discussed here: When does a constexpr function get evaluated at compile time? 这里讨论一个保证对
constexpr
函数进行编译时评估的断言: 何时在编译时评估constexpr函数?
Is a constexpr
+ assert
combination the only guaranteed way to accomplish such conversions at compile-time? constexpr
+ assert
组合是在编译时完成此类转换的唯一保证方法吗?
SOLUTION: 解:
After a lot of head-scratching, I've come to the conclusion, that the convert
function I've provided is unnecessary. 经过大量的努力之后,我得出的结论是,我提供的
convert
函数是不必要的。 The best I could come with was: 我能带的最好的是:
#define CONVERT(T, V) static constexpr T const T##_##V(V)
int main()
{
CONVERT(float, 1);
::std::cout << float_1 << std::endl;
return 0;
}
The best alternative would be a floating_point_constant
counterpart of ::std::integral_constant
, but alas, it is not possible to write one. 最好的选择将是一个
floating_point_constant
对口::std::integral_constant
,但很可惜,这是不可能写一个。
It's even easier than I thought: 它比我想象的还要简单:
int a = 1;
constexpr auto b = convert<float>(a);
does not compile while 不会在编译
const int a = 1;
constexpr auto b = convert<float>(a);
constexpr auto c = convert<float>(1);
constexpr auto d = convert<float>(1 + 2);
constexpr auto e = convert<int>(1.0 + 2.0);
does (with the obvious warnings about unused variables ;-) ) 确实(带有关于未使用变量的明显警告;-))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.