2

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.

Community
  • 1
  • 1
user1095108
  • 14,119
  • 9
  • 58
  • 116
  • I can not get your idea, why not just to write: 12.34f, and this would be constant of float type. – fghj Sep 21 '13 at 15:24
  • Because of possible conversions to `double`, `int` or some other type. I'd like to get the best possible approximation of source value in the destination type at compile-time. – user1095108 Sep 21 '13 at 15:26

1 Answers1

1

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

stefan
  • 10,215
  • 4
  • 49
  • 90
  • Sure, but you need a `constexpr` variable. – user1095108 Sep 21 '13 at 15:35
  • I'd just like to place `convert` invocations inside arbitrary expressions, without worries about run-time invocations. – user1095108 Sep 21 '13 at 15:43
  • i.e. you don't need a convert function for the use-case you presented at all. – user1095108 Sep 21 '13 at 15:44
  • @user1095108 well the convert function is yours. If you want to check if an arbitrary expression is a compile time constant, check once if it compiles with `constexpr auto foo = your_expr;` and then don't worry ever again. I don't see your problem with that. – stefan Sep 21 '13 at 15:46
  • add `static` before `constexpr`, `gdb` shows better code that way (compiler does not put the variables on the stack). – user1095108 Sep 21 '13 at 17:39