c++11 - 当测试条件包括用const定义的常量时,static_assert失败?

标签 c++11 error-handling

我正在阅读Bjarne Stroustrup的书“The C++ Programming Language”,并找到了一个解释static_assert的示例。我了解的是,static_assert仅适用于可以由常量表达式表示的事物。换句话说,它不得包含要在运行时求值的表达式。

书中使用了以下示例(我对代码进行了一些更改。但是,我认为这不应该更改书中提供的原始示例代码产生的任何内容。)

#include <iostream>

using namespace std;

void f (double speed)
{
    constexpr double C = 299792.468;
    const double local_max = 160.0/(60*60);
    static_assert(local_max<C,"can't go that fast");
}

int main()
{
        f(3.25);
    cout << "Reached here!";
    return 0;
}

上面给出了一个编译错误。这是使用ideone编译的:http://ideone.com/C97oF5

本书示例中的确切代码:
constexpr double C = 299792.458;
void f(double speed)
{ 
    const double local_max = 160.0/(60∗60);
    static_assert(speed<C,"can't go that fast"); // yes this is error
    static_assert(local_max<C,"can't go that fast");
 } 

最佳答案

编译器在编译时不知道speed的值。它在编译时无法评估speed < C是有道理的。因此,在处理该行时,预计会出现编译时错误

static_assert(speed<C,"can't go that fast");

该语言不保证在编译时对浮点表达式进行求值。一些编译器可能支持它,但这并不是依赖。

即使浮点变量的值对于人类读者而言是“常数”,也不一定在编译时就对其进行求值。您提供的链接中来自编译器的错误消息使您很清楚。

static_assert expression is not an integral constant expression


您将必须找到一种使用整数表达式进行比较的方法。但是,这似乎是一个有争议的问题。我怀疑,您真正想做的是确保speed在一定范围内。这仅作为运行时检查才有意义。

关于c++11 - 当测试条件包括用const定义的常量时,static_assert失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45379803/

相关文章:

android - 插入外部电话时,Android Studio libGDX不显示错误消息

C++11 线程卡在锁定互斥锁上

c++ - 涉及非推导参数包的函数指针参数类型模板实参推导

函数中的 C 错误 : unknown type name 'FILE' ,

vbscript - "On Error Resume Next"语句有什么作用?

python - python 中的最佳返回类型策略

c++ - 当我使用可变参数时,它适用于 int 和 double,但是当涉及到 float 时,就会出错

c++ - 如何将一个或多个(未定义的数字)参数传递给函数?

c++ - 如何仅从 linux SO 库中导出某些函数?

Python multiprocessing.Pool.map 悄然死去