简体   繁体   中英

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. 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?

Is a constexpr + assert combination the only guaranteed way to accomplish such conversions at compile-time?

SOLUTION:

After a lot of head-scratching, I've come to the conclusion, that the convert function I've provided is unnecessary. 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.

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 ;-) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM