www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How define accepted types in a template parameter?

reply Marcone <marcone email.com> writes:
For example, I want my function template to only accept integer 
or string;
Jan 16
next sibling parent Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= <aferust gmail.com> writes:
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
prev sibling parent Basile B. <b2.temp gmx.com> writes:
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