www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Parameter with indetermined tuple elements type?

reply Marcone <marcone email.com> writes:
I want to create a function that receive a tuple (need be a 
tuple) with indetermined length and indetermined elements type 
without template. The argument need be a tuple, but length and 
elements types indetermineds. How can I make it?
Jan 11
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 1/11/21 7:27 AM, Marcone wrote:
 I want to create a function that receive a tuple (need be a tuple) with 
 indetermined length and indetermined elements type without template. The 
 argument need be a tuple, but length and elements types indetermineds. 
 How can I make it?
With isIntanceOf in a template constraint: import std.traits; import std.typecons; void foo(T)(T t) if (isInstanceOf!(Tuple, T)) { } unittest { static assert(__traits(compiles, foo(tuple(1, "hello")))); static assert(!__traits(compiles, foo(2))); } Or, you can put the check inside the body of the function to display a custom compilation error message: void foo(T)(T t) { static assert (isInstanceOf!(Tuple, T), "I can only work with a Tuple."); } But in that case, the compilation error points at the 'static assert' line, not where the function is called incorrectly from. Ali
Jan 11
prev sibling parent oddp <oddp posteo.de> writes:
On 11.01.21 16:27, Marcone via Digitalmars-d-learn wrote:
 function [...] without template.
And why don't you want to use templates for that? It's as easy as that: import std; auto foo(T)(T tup) if (isTuple!T) { // statically introspect tuple here ... return tup; } void main() { writeln(foo(tuple(1, "2", '3'))); writeln(foo(tuple())); //writeln(foo("not a tuple")); // fails to compile } [1] https://run.dlang.io/is/VYk9Y9
Jan 11