user1095108
user1095108

Reputation: 14623

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.

Upvotes: 2

Views: 1299

Answers (1)

stefan
stefan

Reputation: 10355

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

Upvotes: 1

Related Questions