c++ - 阅读boost/timer.hpp, 为什么代码中将函数括起,再使用函数调用运算符
ringa_lee
ringa_lee 2017-04-17 14:55:20
0
1
548

阅读了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_lee
ringa_lee

ringa_lee

全員に返信(1)
Ty80

是为了防止function-like macro expansion。
比如<Windows.h> 有#define max/min。

像boost这类库要考虑跨平台编译的。
如果不用括号括起,在win平台编译八成会报错,因为虽然max前面有std,但预处理器会对max做expansion(因为Windows.h 有max宏函数影响),之后编译会报一些奇怪的错误。

在这些情况下,你可能会用#undef或其他方法。问题是如果用#undef,你之后可能需要再#include神马的,因为其他地方可能需要已经undef的宏函数。

那为啥加括号比较好呢。因为它跨平台,而且可以使预处理器暂时停止macro expansion

看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.

いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!