ethereum / solidity

Solidity, the Smart Contract Programming Language
https://soliditylang.org
GNU General Public License v3.0
23.01k stars 5.7k forks source link

Generics Implementation #13776

Open NunoFilipeSantos opened 1 year ago

NunoFilipeSantos commented 1 year ago

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:

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.

Out of scope


Resources

  1. Roadmap items
k06a commented 8 months ago

Can’t wait to have this implemented to work properly with structures and their function arguments…