C++编译器能在编译时计算出文字的除法结果吗
Can C++ compiler calculate division result of literals during the compile time
我有下一个代码:
#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;
};
请参阅评论中的问题。
欢迎来到SOC++论坛。您的问题是可以的,它涉及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++。
相关文章:
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 如何使用字符串文字作为宏参数
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 构造<int>具有 2 个字符串文字的向量
- 将数字打印成文字
- 在除法中不需要四舍五入
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 方便地对C++中的所有字符串文字进行模糊处理
- 在TFHE(完全快速同态加密)上执行除法
- 使用 int 表示浮点除法 C++
- C++17 十六进制浮点文字单精度后缀冲突?
- 而循环:简单的除法程序输出零,不明白为什么
- 余数除法和不允许除以零 (c++) 时遇到问题
- 常量函数,当其参数是对文字类型的引用时
- 连接 LPCSTR 变量和文字?
- 如何确定涉及 C++ 中除法的算术表达式的数据类型
- 比较 std::string 和 C 样式字符串文字
- 分配给浮点数的积分文字除法 - 为什么结果是错误的?
- C++编译器能在编译时计算出文字的除法结果吗