Thread overview
Parameter with indetermined tuple elements type?
Jan 11, 2021
Marcone
Jan 11, 2021
Ali Çehreli
Jan 11, 2021
oddp
January 11, 2021
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?
January 11, 2021
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
January 11, 2021
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