c++ - C++编译器可以在编译期间计算文字的除法结果吗
问题描述
我有下一个代码:
#define TIMEOUT_MS = 10000
class Data
{
public:
Data()
: _timeoutMs{TIMEOUT_MS / 1000} // Сan С++ standard guarantee that division will be calculated during the compile time?
{
}
private:
int _timeoutMs = 0;
};
请在评论中查看问题。
解决方案
欢迎来到 SO C++ 论坛。您的问题没问题,它涉及 C++“标准”与编译器“事实上的标准”问题。在这种情况下,后者占上风。
我将非常大胆地展示您的代码变体转换为标准 C++
// g++ prog.cc -Wall -Wextra -std=c++17
#include <iostream>
#include <cstdlib>
// this will not compile
// #define TIMEOUT_MS = 10000
// this will
// #define TIMEOUT_MS 10000
// but avoid macros whenever you can
// constexpr guarantees compile time values
constexpr
auto TIMEOUT_MS{ 10000U } ;
// always use namespaces to avoid name clashes
namespace igor {
// 'struct' is comfortable choice for private types
// 'final' makes for (even) more optimizations
struct data final
{
// standard C++ generates this for you
// data() { }
// do not start a name with underscore
// https://stackoverflow.com/a/228797/10870835
constexpr static auto timeout_ = TIMEOUT_MS / 1000U ;
}; // data
} // igor ns
int main( int , char * [] )
{
using namespace std ;
// for time related computing use <chrono>
cout << boolalpha << igor::data::timeout_ << " s (perhaps)" << endl;
return 42 ;
}
每当您可以发布链接到您的(短!)编译和运行的代码或只是显示问题时。
我使用魔杖盒:https ://wandbox.org/permlink/Fonz5ISoOL1KNJqe
享受标准 C++。
推荐阅读
- spring-boot - JSP页面未在SpringBoot应用程序中呈现
- css - ReferenceError: 窗口未定义导入 css
- mysql - Mysql2::Error "Access denied for user" 在 database.yml 中使用 env 变量
- angular - 通过 getElementById 以编程方式单击 mat-checkbox
- django-queryset - 2个值之间的查询集过滤器带有外键?
- javascript - 如何从 word javascript api 向 http:localhost 发出 GET 请求?
- android - 如何使用 GoogleMaps 绘制 Snake 路径?
- protractor - 如何在钩子后给予黄瓜优先顺序
- python - tkinter 是否包含在 python3 debian 包中?
- c# - How to rename migrations table in entity framework?