首页 > 解决方案 > 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;
};

请在评论中查看问题。

标签: c++

解决方案


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


推荐阅读