Thread overview | |||||
---|---|---|---|---|---|
|
January 18, 2017 Function template advice | ||||
---|---|---|---|---|
| ||||
I have a simple comparison function: struct Foo { string bar; } auto sameGroup(T,S) (T a, S b) { static assert (is(T == string) || is(T == Foo)); static assert (is(S == string) || is(S == Foo)); string aStr; string bStr; static if (is(T == string)){ aStr = a; } else { aStr = a.bar; } static if (is(S == string)){ bStr = b; } else { bStr = b.bar; } return equal (aStr,bStr); } This works, but just wondered if there was an easier way? Is there a way to do "static if" in shorthand, like: auto aStr = (static if (is(T==string)) ? a : a.bar |
January 18, 2017 Re: Function template advice | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jordan Wilson | On 01/18/2017 02:02 PM, Jordan Wilson wrote:
> I have a simple comparison function:
>
> struct Foo {
> string bar;
> }
>
> auto sameGroup(T,S) (T a, S b) {
> static assert (is(T == string) || is(T == Foo));
> static assert (is(S == string) || is(S == Foo));
>
> string aStr;
> string bStr;
> static if (is(T == string)){
> aStr = a;
> } else {
> aStr = a.bar;
> }
> static if (is(S == string)){
> bStr = b;
> } else {
> bStr = b.bar;
> }
> return equal (aStr,bStr);
> }
>
> This works, but just wondered if there was an easier way?
>
> Is there a way to do "static if" in shorthand, like:
> auto aStr = (static if (is(T==string)) ? a : a.bar
Yes, can be better with something similar to the following:
struct Foo {
string bar;
}
string value(U : Foo)(U u) {
return u.bar;
}
string value(U : string)(U u) {
return u;
}
auto sameGroup(T,S) (T a, S b) {
static assert (is(T == string) || is(T == Foo));
static assert (is(S == string) || is(S == Foo));
import std.algorithm;
return equal (value(a), value(b));
}
void main() {
assert(sameGroup("a", "b") == false);
assert(sameGroup("a", Foo("a")) == true);
assert(sameGroup(Foo("x"), "b") == false);
assert(sameGroup(Foo("z"), Foo("z")) == true);
}
Ali
|
January 18, 2017 Re: Function template advice | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Wednesday, 18 January 2017 at 22:39:02 UTC, Ali Çehreli wrote:
> On 01/18/2017 02:02 PM, Jordan Wilson wrote:
>> [...]
>
> Yes, can be better with something similar to the following:
>
> struct Foo {
> string bar;
> }
>
> string value(U : Foo)(U u) {
> return u.bar;
> }
>
> string value(U : string)(U u) {
> return u;
> }
>
> auto sameGroup(T,S) (T a, S b) {
> static assert (is(T == string) || is(T == Foo));
> static assert (is(S == string) || is(S == Foo));
>
> import std.algorithm;
> return equal (value(a), value(b));
> }
>
> void main() {
> assert(sameGroup("a", "b") == false);
> assert(sameGroup("a", Foo("a")) == true);
> assert(sameGroup(Foo("x"), "b") == false);
> assert(sameGroup(Foo("z"), Foo("z")) == true);
> }
>
> Ali
Nice, yes looks better thanks.
Jordan
|
Copyright © 1999-2021 by the D Language Foundation