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;
};

请参阅评论中的问题。

欢迎来到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++。

最新更新