Using a tuple as a function parameter
user1234
user1234 at 12.de
Fri Nov 22 17:20:33 UTC 2024
On Friday, 22 November 2024 at 16:36:43 UTC, Andrew wrote:
> I'm getting started using D for some small personal projects
> and one thing I wanted to do was use a helper function for a
> tuple. I declared the function like this:
>
> string getOrZeroth(Tuple!(string, string, string) tup, int
> i) pure {
> return tup[i] == "" ? tup[0] : tup[i];
> }
>
> and would like to use it like this:
>
> auto foo = tuple("a", "", "c");
> writeln(foo.getOrZeroth(1)); // prints a
>
> but when I try it, I'm getting the below error:
>
>> Error: variable \`i\` cannot be read at compile time
>
> It would probably make more sense to create a class and make
> that a member function, but at this point I'm mostly just
> curious about how to use a tuple as a function parameter. I
> tried using a couple different options like `tuple` and
> `TypeTuple` as well as trying to convert the function into a
> template, but didn't have any better luck with those. I feel
> like I'm probably missing something silly, and any help would
> be appreciated.
tuples elements must be retrieved with indexes that are known at
compile time (integer literals or enum members). You pass one but
this becomes a value that's not known inside the body
so you can use a template value parameter instead:
```
string getOrZeroth(int i)(Tuple!(string, string, string) tup)
{
return tup[i] == "" ? tup[0] : tup[i];
}
```
and use it like that:
```
writeln(foo.getOrZeroth!(1)); // prints a
```
More information about the Digitalmars-d-learn
mailing list