digitalmars.D.learn - How make Optional pre determined parameter type without overload
- Marcone (4/4) Nov 28 2020 void a(T1, T2)(T1 b, T2 c){
- =?UTF-8?Q?Ali_=c3=87ehreli?= (15/19) Nov 28 2020 Since it's optional, T2 must have a default type. I made it 'int' below.
void a(T1, T2)(T1 b, T2 c){ // I need parameter "c" optional, but only (String or int). How can I make it without overload function? }
Nov 28 2020
On 11/28/20 6:40 PM, Marcone wrote:void a(T1, T2)(T1 b, T2 c){ =C2=A0=C2=A0=C2=A0=C2=A0// I need parameter "c" optional, but only (St=ring or int). How can=20I make it without overload function? }Since it's optional, T2 must have a default type. I made it 'int' below. void a(T1, T2 =3D int)(T1 b, T2 c =3D T2.init) if (is (T2 =3D=3D string) || is (T2 =3D=3D int)) { // ... } void main() { a(1.5); a(2.5, "hello"); a(3.5, 42); static assert(!__traits(compiles, a(4.5, 5.5))); }
Nov 28 2020
On Sunday, 29 November 2020 at 02:55:02 UTC, Ali Çehreli wrote:On 11/28/20 6:40 PM, Marcone wrote:Thank you! work fine!void a(T1, T2)(T1 b, T2 c){ // I need parameter "c" optional, but only (String or int). How can I make it without overload function? }Since it's optional, T2 must have a default type. I made it 'int' below. void a(T1, T2 = int)(T1 b, T2 c = T2.init) if (is (T2 == string) || is (T2 == int)) { // ... } void main() { a(1.5); a(2.5, "hello"); a(3.5, 42); static assert(!__traits(compiles, a(4.5, 5.5))); }
Nov 28 2020
Now my slice works fine. // Tipo Nulo. class None {} // Função slice() auto slice(T1, T2, T3 = None)(T1 conteudo, T2 inicio, T3 fim = T3.init) { int start, end, startlen; static if (is(T2 == int)) {inicio = inicio < 0 ? conteudo.length + inicio : inicio;} static if (is(T3 == int)) {fim = fim <= 0 ? conteudo.length + fim : fim;} static if (is(T2 == int)) {start = inicio;} else static if (is(T2 == string)){start = conteudo.countUntil(inicio);} static if (is(T2 == string)) {static if (is(T1 == string)){startlen = start + inicio.length + 1;} else {startlen = start + 1;}} static if (is(T3 == int)) {end = fim;} else static if (is(T3 == string)){end = startlen + conteudo[startlen..$].countUntil(fim);} static if (is(T3 == None)) {return conteudo[start];} else {return conteudo[start..end];} }
Dec 02 2020