How define accepted types in a template parameter?
Basile B.
b2.temp at gmx.com
Sat Jan 16 20:46:50 UTC 2021
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
More information about the Digitalmars-d-learn
mailing list