| Thread overview | ||||||||
|---|---|---|---|---|---|---|---|---|
|
July 12, 2017 Function with static array as parameter | ||||
|---|---|---|---|---|
| ||||
What is the best way in D to create a function that receives a static array of any length? | ||||
July 12, 2017 Re: Function with static array as parameter | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Miguel L | On Wednesday, 12 July 2017 at 12:20:11 UTC, Miguel L wrote:
> What is the best way in D to create a function that receives a static array of any length?
Templatize the array length:
void foo(size_t length)(int[length] arr)
{
}
| |||
July 12, 2017 Re: Function with static array as parameter | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Miguel L | On Wednesday, 12 July 2017 at 12:20:11 UTC, Miguel L wrote:
> What is the best way in D to create a function that receives a static array of any length?
You will need to use templates:
void foo(size_t N)(int[N] arr) {
}
--
Biotronic
| |||
July 12, 2017 Re: Function with static array as parameter | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Rene Zwanenburg | On Wednesday, 12 July 2017 at 12:57:19 UTC, Rene Zwanenburg wrote:
> On Wednesday, 12 July 2017 at 12:20:11 UTC, Miguel L wrote:
>> What is the best way in D to create a function that receives a static array of any length?
>
> Templatize the array length:
>
> void foo(size_t length)(int[length] arr)
> {
>
> }
That being said, this may lead to template bloat and excessive copying. What are you trying to do? Is there a reason you can't use a slice?
| |||
July 12, 2017 Re: Function with static array as parameter | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Miguel L | On Wednesday, 12 July 2017 at 12:20:11 UTC, Miguel L wrote:
> What is the best way in D to create a function that receives a static array of any length?
Do know that static arrays are passed by value in D, so passing a static array of a million elements will copy them...
There are two solutions to this:
1) pass the static array by reference. This will pass a pointer to the array and won't copy it although modifying it will modify the original. consider passing const ref if the function doesn't modify it. Although will still create its of template bloat.
2) pass a slice of the static array. this is essentially the same as the above, but you also pass the length of the array as well. This means it can accept a slice of a static array of any size (or any dynamic array) and since it isn't a template the compiler won't make lots of copies for different sized array. This is probably he better option.
| |||
July 13, 2017 Re: Function with static array as parameter | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Nicholas Wilson | Thanks for your help. | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply