Thread overview
How define accepted types in a template parameter?
Jan 16
Marcone
Jan 16
Basile B.
January 16
For example, I want my function template to only accept integer or string;
January 16
On Saturday, 16 January 2021 at 18:39:03 UTC, Marcone wrote:
> For example, I want my function template to only accept integer or string;

There are different ways of doing that. I'd say this one is easy to follow:

import std.stdio;

void print(T)(T entry) if(is(T==string) || is(T==int))
{
	writeln(entry);

}

void main(){
    int i = 5;
    string foo = "foo";

    double j = 0.6;

    print(i);
    print(foo);
    print(j); // compilation error
}
January 16
On Saturday, 16 January 2021 at 18:39:03 UTC, Marcone wrote:
> For example, I want my function template to only accept integer or string;

You can do that with either

- `static if` inside the body [1]

  import std.traits;
  void foo(T)(T t)
  {
    static if (isIntegral!T) {}
    else static assert false;
  }


- template constraint [2]

  import std.traits;
  void foo(T)(T t)
  if (isIntegral!T)
  {
  }

- template parameter specialization [3]

  void foo(T : ulong)(T t) // : meaning implictly convert to
  {
  }


2 and 3 being the more commonly used.
1 is more to use the same body instead of using N overloads

[1] : https://dlang.org/spec/version.html#staticif
[2] : https://dlang.org/spec/template.html#template_constraints
[3] : https://dlang.org/spec/template.html#parameters_specialization