Skip to content

Generics Implementation #13776

@NunoFilipeSantos

Description

@NunoFilipeSantos

What

Solidity should support template types/generics for contracts, libraries, functions, and structs.

Why

TBD

How

TBD

Tasks

  •  TBD

Notes

#869 (comment)
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

  • TBD

Resources

  1. Roadmap items

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions