3 ms·
Using statement expressions and the typeof extension, you are able to write function-like, type-generic, scope-insensitive macros like this one: #define MA
by bluetomcat 11y ago
Using statement expressions and the typeof extension, you are able to write function-like, type-generic, scope-insensitive macros like this one:
#define MAX(a,b) ({ \
typeof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; \
})
The inability to write template functions can be compensated by designing your function so that it takes a function pointer where the type-specific action occurs.
- nly 11y agoYour MAX has no respect for namespaces or scopes. A real world macro is probably going to be called MYLIBRARY_MAX to avoid this. Secondly the C++ lambda solution is just easier to read. auto max = [](auto a, auto b) { return (a > b) ? a : b; }; max (3.1415, 42); // returns double max (42ul, 78u); // returns unsigned long max (17, 16); // returns int
- f00fc0d3 11y agoTypeof is not standard and many DSP compilers do not implement that. Secondly I meant max search in array, not between to scalar values which is trivial. I really don't want to have for(...) inlined everywhere.