在Clang中实现min()和max(),而不进行双重评估 [英] Implementing min() and max() in Clang without double evaluation

查看:245
本文介绍了在Clang中实现min()和max(),而不进行双重评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

min 函数的典型预处理版本如下所示:

The classic preprocessor version of the min function looks like

#define min(a, b) ((a) < (b) ? (a) : (b))

这让你开始进行双重评估 - 你做 min(f(),g()),忘记了 f g 有副作用,你必须花几个小时来弄清楚为什么你的函数运行两次。要避免这种情况,您可以执行

This leaves you open to double evaluation—the situation in which you do min(f(), g()), forgetting that f or g has side effects, and you have to spend hours trying to figure out why your function is running twice. To prevent this, you can do

#define min(a, b) ({__typeof__(a) _a = (a); \
    __typeof__(b) _b = (b); \
    _a < _b ? _a : _b;})

这在GCC下工作得很好,但是如果你通过Clang运行它 -Wgnu -pedantic 的伞 - 你会得到像

This works great under GCC, but if you run it through Clang with -Wgnu set—this set of warnings falls under the umbrella of -pedantic—you get errors like

test.c:5:10: error: use of GNU statement expression extension [-Werror,-Wgnu]
        int a = min(3, 7);
                ^
test.c:1:22: note: expanded from macro 'min'
#  define min(a, b) ({__typeof__(a) _a = (a); __typeof__(b) _b = (b); _a < _b ? _a : _b;})

它可以定义这些宏,以防止双重评价这是Clang在 -pedantic 下可以接受? (是的,你可以用 -Wno-gnu 禁用警告,在这种情况下,Clang处理语句表达式没有问题,我问,因为我,如 clang -pedantic ,太挑剔了我自己的好。)

Is it possible to define these macros in a way that prevents double evaluation and which is acceptable to Clang under -pedantic? (Yes, you can disable the warning with -Wno-gnu, in which case Clang handles the statement expression without a problem. I’m asking because I, like clang -pedantic, am too picky for my own good.)

编辑:在C。我标记这个C ++太,因为我认为一个解决方案可能适用于C + +以及C. Oops - 忘了模板!

I am working in C. I tagged this C++ too because I thought a solution might apply to C++ as well as to C. Oops—forgot about templates! Sorry for the ambiguity.

推荐答案

如果你真的用C ++编写,只需不要使用预处理器

If you're really writing in C++, simply don't use the preprocessor:

template <typename T>
const T min(const T& a, const T& b)
{
   return (b < a) ? b : a;
}

(注意,我已经交换 b a ,所以如果两个操作数相等,就得到左边的操作数。)

(Note that I've swapped b and a, so that you get the left-hand operand if the two are equal.)

否则不,不是真的

这篇关于在Clang中实现min()和max(),而不进行双重评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆