Constexpr variable and division

I am trying to evaluate this simple expression at compile time using C ++ 11's new constexpr function:

template <int a, int b>
class Test
{
   static constexpr double c = a / b;
};

      

But here's what Klang tells me:

Constexpr variable 'c' must be initialized by a constant expression

      

The strange thing is that the following compilations are good:

template <int a, int b>
class Test
{
   static constexpr double c = a / 2.f;
};

      

Do you have any ideas as to why a / b is not a constant expression and how I can evaluate this at compile time?

Using the Clang compiler with -std = c ++ 1y and -stdlib = libc ++

Refresh

The following example throws an error with source code:

Test<10,0> test1 ;

      

and

Test<10,1> test1 ;

      

not.

+2


source to share


2 answers


Cause:

Test<10,0> test1 ;

      

doesn't work because you undefined behavior due to division by zero. This is described in the standard section of the C ++ project 5.6

[expr.mul], which says:



If the second operand / or% is zero, the behavior is undefined

and constant expressions specifically exclude undefined behavior . I'm not sure which version clang

you are using, but the versions I have available on the internet provide a divide by zero warning ( see it live ):

note: division by zero
static constexpr double c = a / b;
                              ^

      

+3


source


solvable. One of the template instances had b=0

. Somehow, Klang didn't warn me that I was dividing by zero. And is +Inf

not a constant expression.



+1


source







All Articles