Thread overview | |||||
---|---|---|---|---|---|
|
February 09, 2021 Traits of variadic templates | ||||
---|---|---|---|---|
| ||||
Let's say I have... void foo(T...)(T xs) { foreach(x; xs) { if (typeid(x) == typeid(int)) writeln("int: ", x); else writeln("str: ", x); } } From the body, it's obvious I really only want int or string to be passed in to foo. Ideally, this check would be done at compile-time. Obviously, I could modify foo to something like: void foo(Algebraic!(int, string)[] xs) I could also put checks in the body at runtime. But, for the sake of this thread, let's not. ;-) What would be ideal (IMO) would be something along the lines of: void foo(T...)(T xs) if (isIntegral!T || isSomeString!T) But, those don't work because T is a Tuple of the types. Is there some trait combination I can use to do this? Something like (obviously made up)... all(TemplateArgsOf!T, t => isIntegral!t || isSomeString!t) Thanks! |
February 09, 2021 Re: Traits of variadic templates | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jeff | On Tuesday, 9 February 2021 at 16:22:16 UTC, Jeff wrote: > But, those don't work because T is a Tuple of the types. Is there some trait combination I can use to do this? Something like (obviously made up)... > > all(TemplateArgsOf!T, t => isIntegral!t || isSomeString!t) > > Thanks! import std.meta: allSatisfy, Or = templateOr; allSatisfy!(Or!(isIntegral, isSomeString), T); http://phobos.dpldocs.info/std.meta.allSatisfy.html http://phobos.dpldocs.info/std.meta.templateOr.html |
February 09, 2021 Re: Traits of variadic templates | ||||
---|---|---|---|---|
| ||||
Posted in reply to Paul Backus | On Tuesday, 9 February 2021 at 16:25:46 UTC, Paul Backus wrote:
> On Tuesday, 9 February 2021 at 16:22:16 UTC, Jeff wrote:
>> But, those don't work because T is a Tuple of the types. Is there some trait combination I can use to do this? Something like (obviously made up)...
>>
>> all(TemplateArgsOf!T, t => isIntegral!t || isSomeString!t)
>>
>> Thanks!
>
> import std.meta: allSatisfy, Or = templateOr;
> allSatisfy!(Or!(isIntegral, isSomeString), T);
>
> http://phobos.dpldocs.info/std.meta.allSatisfy.html
> http://phobos.dpldocs.info/std.meta.templateOr.html
Thanks so much!
|
Copyright © 1999-2021 by the D Language Foundation