April 09, 2017 Variable Arguments | ||||
---|---|---|---|---|
| ||||
void foo(A...)(A a) { foreach(aa; a) { for(int i = 0; i < a.length; i++) ... } } A can be strings or char, how can I easily deal with both? (e.g., a.length = 1 for a being a char... and also a[0] = a, so to speak). That is, I want chars to be treated as strings of length 1, since I have written my code to work with strings, no reason it shouldn't work with chars. I realize we can't use the above notation but I can't get the type of aa because D complains it is unknown at compile time. I could use A[k] but it requires extra work. |
April 09, 2017 Re: Variable Arguments | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jethro | On 09/04/2017 7:30 AM, Jethro wrote:
> void foo(A...)(A a)
> {
> foreach(aa; a)
> {
> for(int i = 0; i < a.length; i++)
> ...
> }
> }
>
> A can be strings or char, how can I easily deal with both? (e.g.,
> a.length = 1 for a being a char... and also a[0] = a, so to speak).
>
> That is, I want chars to be treated as strings of length 1, since I have
> written my code to work with strings, no reason it shouldn't work with
> chars. I realize we can't use the above notation but I can't get the
> type of aa because D complains it is unknown at compile time. I could
> use A[k] but it requires extra work.
A char and a string is no where near the same thing.
A char is a single byte, a string is a array which is made up of a pointer to a set of chars plus a length (size_t WORD size of cpu e.g. 4/8 bytes).
You would need to wrap up that input char e.g. string s = cast(immutable)[c];
But here is what I would recommend:
void foo(char[] c...) {
string[] args;
foreach(v; c) {
args ~= cast(immutable)[c]
}
foo(args);
}
void foo(string[] s...) {
// ...
}
This will remove the need for template specialization (or "implicit" support for e.g. wstring and dstring).
|
Copyright © 1999-2021 by the D Language Foundation