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

 藏A组合别_577 发布于 2022-11-05 13:23

阅读了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::max)())
       - double(_start_time)) / double(CLOCKS_PER_SEC); 
  }

其中,

double((std::numeric_limits::max)())

为什么要先将

std::numeric_limits::max

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

谢谢大家。

1 个回答
  • 是为了防止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.

    2022-11-12 01:55 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有