function min<T>(T a, T b) pure internal returns (T ret) {
ret = (a < b) ? a : b;
}
function max<T>(T a, T b) pure internal returns (T ret) {
ret = (a > b) ? a : b;
}
function abs<T: T.isSigned>(T a) pure internal returns (T ret) {
ret = (a < 0) ? -a : a;
}
While the abs case does not strictly require the capability to enforce it is on a signed type (the < 0 may be a compile time failure with an unsigned type), it certainly helps clarity. Similarly to T.isSigned we could have something like T.toUnsignedType (aka C++ has), if we wanted to do type conversion at the end of abs.
Should we have more type inspection capabilities, we could introduce further restrictions on what types are accepted, such as isIntegral, isFixedPoint, etc. However even the above version would be sufficient to be used with int/uint/fixed types, while others would just throw a compile time error for invalid comparison operator.
Another questions springs to mind: what about variadic functions? min could be nice with variadic number of arguments, though that is something we may not actually want.
What
Solidity should support template types/generics for contracts, libraries, functions, and structs.
Why
TBD
How
TBD
Tasks
Notes
https://github.com/ethereum/solidity/issues/869#issuecomment-823600859 Here are three very simple functions which can come handy in many applications:
While the abs case does not strictly require the capability to enforce it is on a signed type (the < 0 may be a compile time failure with an unsigned type), it certainly helps clarity. Similarly to T.isSigned we could have something like T.toUnsignedType (aka C++ has), if we wanted to do type conversion at the end of abs.
Should we have more type inspection capabilities, we could introduce further restrictions on what types are accepted, such as isIntegral, isFixedPoint, etc. However even the above version would be sufficient to be used with int/uint/fixed types, while others would just throw a compile time error for invalid comparison operator.
Another questions springs to mind: what about variadic functions? min could be nice with variadic number of arguments, though that is something we may not actually want.
Out of scope
Resources