digitalmars.D.learn - Default arguments
- Salih Dincer (77/77) Feb 07 2023 Hi All...
- Salih Dincer (20/24) Feb 07 2023 You should use `@disable this()` recommended in the relevant
Hi All...
Is it a feature or a bug that the code below can be compiled
without arguments?
```d
import std.stdio, std.conv : to;
void main()
{
auto noArgument = Sarr!char(); // it works no argument...
assert(noArgument.length == 8);
string dlang = "D-lang";
const len = dlang.length;
auto withArgument = Sarr!char(dlang.dup); // complied
assert(withArgument.arr[0..len].to!string == dlang);
}
template Sarr(alias T = char)
{
enum s = size_t.sizeof / T.sizeof;
struct Sarr
{
T[s] arr = T(0);
auto length = s;
this(A)(A[] arr) in(s >= arr.length)
{
foreach(i, e; arr)
{
this.arr[i] = cast(T)e;
}
}
}
}
```
I want to learn one more thing. Why can't the default argument be
used in alias of structs? Voldemort types work just fine for
example:
```d
template Farr(alias T = char)
{
enum s = size_t.sizeof / T.sizeof;
struct Result
{
T[s] arr = T(0);
auto length = s;
}
Result Farr(A)(A[] arr) in(s >= arr.length)
{
Result result;
foreach(i, e; arr)
{
result.arr[i] = cast(T)e;
}
return result;
}
}
import std.stdio;
void main()
{
auto arr = [ 'd', 'e' ];
auto foo = Farr(arr);
foo.writeln; // Result("de\0\0\0\0\0\0", 8)
// auto bar = Sarr(arr); // no complied
}
unittest
{
auto arr = [ 'd', 'e' ];
ref auto addAndReturn(T)(ref T[] arr) {
auto a = arr[$-1];
return arr ~= ++a;
}
auto len2 = Sarr!int(arr);
assert(len2.length == 2);
auto len4 = Sarr!short(addAndReturn(arr)); // add 'f'
assert(len4.length == 4);
auto len8 = Sarr!byte(addAndReturn(arr)); // add'g'
assert(len8.length == 8);
}
```
SDB 79
Feb 07 2023
On Tuesday, 7 February 2023 at 09:49:46 UTC, Salih Dincer wrote:Is it a feature or a bug that the code below can be compiled without arguments?You should use ` disable this()` recommended in the relevant article: https://dlang.org/spec/struct.html#disable_default_construction ```d void main() { auto noArgument = Sarr!char(); // no compile } ``` On Tuesday, 7 February 2023 at 09:49:46 UTC, Salih Dincer wrote:I want to learn one more thing. Why can't the default argument be used in alias of structs?```d void main() { auto bar = Sarr!()(dlang.dup); // complied assert(is(typeof(bar.arr[0]) == char)); } ``` 😀 SDB 79
Feb 07 2023








Salih Dincer <salihdb hotmail.com>