问题描述
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;
}
否则。
这篇关于在Clang中实现min()和max(),而不进行双重评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!