0

I have next code:

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

Please see question in the comment.

Igor
  • 1,029
  • 9
  • 21

1 Answers1

2

Welcome to SO C++ forum. Your question is OK, it touches on C++ "standard" vs compilers "de-facto standards" issue. In this instance the later prevails.

I will be so bold to present variant of your code transformed into standard 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 ;
  }

Whenever you can post the link to your (short!) code that compiles and runs or just show the problem.

I use wandbox : https://wandbox.org/permlink/Fonz5ISoOL1KNJqe

Enjoy the standard C++.

Quentin
  • 62,093
  • 7
  • 131
  • 191
Chef Gladiator
  • 902
  • 11
  • 23
  • `_timeoutMs` is fine since it is not in the global namespace. Otherwise, nice refactoring. – Quentin Oct 25 '19 at 08:51
  • @Quentin thank's, although, I prefer my team not to do things standard does not allow, even they can be done in some context. – Chef Gladiator Oct 25 '19 at 08:56
  • Well, only `::` is concerned, and since you're observing the "always namespace your code" rule it won't ever apply :) – Quentin Oct 25 '19 at 08:58