Thread overview | |||||
---|---|---|---|---|---|
|
February 21, 2021 How can I check if template variable parameter is iterable before handle it? | ||||
---|---|---|---|---|
| ||||
import std; void foo(T)(T bar){ static if (bar.isiterable()) // Need Somethin to check if bar is iterable. { // Execute it if bar is iterable. foreach (i; bar) { } } else { // Execute it if bar is NOT iterable. } } void main(){ foo(1); foo([1, 2, 3, 4, 5]); } |
February 21, 2021 Re: How can I check if template variable parameter is iterable before handle it? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marcone | On Sunday, 21 February 2021 at 11:58:11 UTC, Marcone wrote: > import std; > > void foo(T)(T bar){ > static if (bar.isiterable()) // Need Somethin to check if bar is iterable. > { > // Execute it if bar is iterable. > foreach (i; bar) > { > > } > } > else { > // Execute it if bar is NOT iterable. > } > > } > > void main(){ > foo(1); > foo([1, 2, 3, 4, 5]); > } https://dlang.org/library/std/traits/is_iterable.html import std.traits : isIterable; void foo(T)(T bar){ static if (isIterable!T) { ... |
February 21, 2021 Re: How can I check if template variable parameter is iterable before handle it? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Boris Carvajal | On Sunday, 21 February 2021 at 12:47:46 UTC, Boris Carvajal wrote:
> On Sunday, 21 February 2021 at 11:58:11 UTC, Marcone wrote:
>> import std;
>>
>> void foo(T)(T bar){
>> static if (bar.isiterable()) // Need Somethin to check if bar is iterable.
>> {
>> // Execute it if bar is iterable.
>> foreach (i; bar)
>> {
>>
>> }
>> }
>> else {
>> // Execute it if bar is NOT iterable.
>> }
>>
>> }
>>
>> void main(){
>> foo(1);
>> foo([1, 2, 3, 4, 5]);
>> }
>
> https://dlang.org/library/std/traits/is_iterable.html
>
> import std.traits : isIterable;
>
> void foo(T)(T bar){
> static if (isIterable!T)
> {
> ...
Thank you.
// Function isiterable()
bool isiterable(T)(T arg) nothrow {try {static if (isIterable!T){return true;} else {return false;}} catch(Throwable){return false;}}
|
Copyright © 1999-2021 by the D Language Foundation