问题描述
我正在尝试使用C ++ 11的新constexpr功能在编译时评估这个简单表达式:
I'm trying to evaluate this simple expression at compile time using C++11 new constexpr feature:
template <int a, int b>
class Test
{
static constexpr double c = a / b;
};
但是Clang一直在告诉我:
But here's what Clang keeps telling me:
Constexpr variable 'c' must be initialized by a constant expression
奇怪的是,以下代码编译得很好:
The weird thing is that the following compiles well:
template <int a, int b>
class Test
{
static constexpr double c = a / 2.f;
};
你们对为什么a / b不是常数表示有什么想法,我怎么知道
Do you guys have any idea on why a/b is not a constant expression, and how could I evaluate this at compile time?
使用带有-std = c ++ 1y和-stdlib = libc ++的Clang编译器
Using Clang compiler with -std=c++1y and -stdlib=libc++
更新
下面的示例使用原始代码导致错误:
The following example causes the error with the original code:
Test<10,0> test1 ;
同时:
Test<10,1> test1 ;
没有。
推荐答案
原因如下:
Test<10,0> test1 ;
失败是因为您拥有,原因是被零除。 C ++标准草案的 5.6
[expr.mul] 中对此进行了说明,其中说:
fails is because you have undefined behavior due to division by zero. This is covered in the draft C++ standard section 5.6
[expr.mul] which says:
和。我不确定您使用的是 clang
的哪个版本,但是我在线上提供的版本确实提供了除以零警告( ):
and constant expressions specifically exclude undefined behavior. I am not sure what version of clang
you are using but the versions I have available online do provide a divide by zero warning (see it live):
note: division by zero
static constexpr double c = a / b;
^
这篇关于Constexpr变量和除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!