Template specialisation, "Generic type locking", offline stdlib docs and case-based template question
user1234
user1234 at 12.nl
Fri Dec 1 04:03:10 UTC 2017
On Friday, 1 December 2017 at 03:39:12 UTC, helxi wrote:
> 1. Template specialisation.
> Why is this useful?:
> T getResponse(T = int)(string question); And how does it differ
> from
> int getResponse(string question); ?
Good Q. Without thinking more it looks like a pointless example.
The only difference i see is that the templatized version won't
get compiled unless used.
> Context: http://ddili.org/ders/d.en/templates.html : Section:
> "Default template parameters"
>
> 2. "Generic locking".
> Is it possible to specialise templates for a certain group of
> types? For example
> auto fn(T)(T arg)
> auto fn(T : int, double, float, ulong)(T arg); //shares same
> behaviour
> auto fn(T : char, string, dchar, wchar, dstring, wstring)(T
> arg); // shares same behavior
You can use template constraints:
auto fn(T)(T arg)
if (is(T==int) || is(T==double) || is(T==float) || is(T==ulong)){}
auto fn(T)(T arg)
if (is(T==char) || is(T==string) || is(T==dchar) ||
is(T==wchar)){}
> 3. "Offline docs".
> Is there any offline documentation of the stdlib? Like
> https://en.cppreference.com/mwiki/index.php?title=Cppreference:Archives&oldid=95461
Yes, distributes with each release. look inside the 7z archive.
On linux it's setup
here: /usr/share/dmd/html/d/phobos/
> 4. Case based question regarding templates:
>
> class Stack(T)
> {
> private:
> T[] data;
> public:
> this(T)(T[] data){ /*..*/}
> this(T)(){}
>
> //...
>
> }
>
> void main()
> {
> auto s = new Stack!int;
> }
>
> Says:
> Error: template app.Stack!int.Stack.__ctor cannot deduce
> function from argument types !()(), candidates are:
> source/app.d(6,2): app.Stack!int.Stack.__ctor(T)(T[]
> data)
> source/app.d(9,2): app.Stack!int.Stack.__ctor(T)()
>
> Why is Stack!int a ctor()() instead of a ctor(int)()?
You must use another identifier here
class Stack(T)
{
private:
T[] data;
public:
this(TT)(TT[] data){ /*..*/}
this()(){}
//...
}
More information about the Digitalmars-d-learn
mailing list