search

Home  >  Q&A  >  body text

c++ - 阅读boost/timer.hpp, 为什么代码中将函数括起,再使用函数调用运算符

阅读了boost/timer.hpp,里面有一段代码不知道为什么这样写。

double elapsed_max() const   
  // return estimated maximum value for elapsed()
  // Portability warning: elapsed_max() may return too high a value on systems
  // where std::clock_t overflows or resets at surprising values.
  {
    return (double((std::numeric_limits<std::clock_t>::max)())
       - double(_start_time)) / double(CLOCKS_PER_SEC); 
  }

其中,

double((std::numeric_limits<std::clock_t>::max)())

为什么要先将

std::numeric_limits<std::clock_t>::max

用括号括起,在使用函数调用运算符呢?

谢谢大家。

ringa_leeringa_lee2813 days ago602

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:57:20

    is to prevent function-like macro expansion.
    For example, <Windows.h> has #define max/min.

    Libraries such as boost should consider cross-platform compilation.
    If you don’t use parentheses, 80% of the time, an error will be reported when compiling on the win platform, because although there is std in front of max, the preprocessor will expand max (because Windows.h has the influence of the max macro function), and some errors will be reported when compiling later. Weird error.

    In these cases, you might use #undef or other methods. The problem is that if you use #undef, you may need to #include Shenma again later, because other places may need the already undefed macro function.

    Then why is it better to add parentheses? Because it is cross-platform and can make the preprocessortemporarily stopmacro expansion

    See c11 7.1.4 Use of library functions

    Any function declared in a header may be additionally implemented as a
    function-like macro defined in the header, so if a library function is
    declared explicitly when its header is included, one of the techniques
    shown below can be used to ensure the declaration is not affected by
    such a macro. Any macro definition of a function can be suppressed
    locally by enclosing the name of the function in parentheses, because
    the name is then not followed by the left parenthesis that indicates
    expansion of a macro function name.

    reply
    0
  • Cancelreply