by f00fc0d3 · 11y ago · 0 comments
I am working in DSP project which was started with typical C++ OO BS, finally with ended up with C compiled as C++ + some simple templates for cases as above.
int maxi(int, int);
double: maxd(double, double);
...
#define max(x) _Generic((x), int: maxi, double: maxd, ...default: maxi)How is it template 'nonsense', when those templates do exactly that?
#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. 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