digitalmars.D.learn - How define accepted types in a template parameter?
- Marcone (2/2) Jan 16 2021 For example, I want my function template to only accept integer
- Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= (16/18) Jan 16 2021 There are different ways of doing that. I'd say this one is easy
- Basile B. (25/27) Jan 16 2021 You can do that with either
For example, I want my function template to only accept integer or string;
Jan 16 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;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 }
Jan 16 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
Jan 16 2021