Doc Comments /
Template
Templates
Messages
Add your comments here...
struct template
Apparently, a struct template can be declared in a similar fashion to how a class template can be declared. This suggested content is designed to explain this behavior.
StructTemplateDeclaration: struct Identifier ( TemplateParameterList ) { DeclDefs }If a template declares exactly one member, and that member is a struct with the same name as the template:
template Bar(T) { struct Bar { T member; } }then the semantic equivalent, called a StructTemplateDeclaration can be written as:
struct Bar(T) { T member; }Inspired by: NG:digitalmars.D/3895
Template Linker Problem
I have a library with one template function in it
template array_case(T) { void array_change_key_case ( T[ char [] ] map) { foreach ( inout char [] keys;map.keys ) { keys = std.string.tolower(keys ); } } }However when I build the lib, I get the error
Symbol Undefined _D3phd5array13array_case_Aa21array_change_key_caseFHAaAaZvIf i eliminate the template and just make them functions it works fine.
Source: NG:digitalmars.D.learn/1030
Kludgy Solution to Linker Problem
The problem is that when templates are instantiated, they are inserted into an object file record called a COMDAT. COMDATs have the necessary feature that if multiple object files have a COMDAT with the same name, the duplicates are discarded.
This feature is necessary for template instantiations, since the compiler compiling one module doesn't know about the same templates being instantiated by another module.
An unfortunate side effect is that the one cannot pull object files out of a library by referencing COMDATs alone, one must reference something else in that object file, too.
The dmdscript.lib library (part of DMDScript) has the same problem with protoerror.d. I solved it with the kludge of inserting:
int foo;into the file, and then referencing it in dobject.d with:
int* pfoo = &dmdscript.protoerror.foo;Not too pretty, but it works.
Based on: NG:digitalmars.D/23701
An slightly better soloution (using a mixin)
int comdatKludge = 0; template kludge () { int * kludge = &comdatKludge; }into the library, then the client just calls
mixin kludge;Source: NG:digitalmars.D.learn/1034
How does D handle non-deduced contexts?
Does D have the same problem as C++ w.r.t. non-deduced contexts, as described in section 14.8.2.4p4 of the c++ standard and as discussed in the following thread: http://groups.google.com/group/comp.lang.c++.moderated/msg/2cb76b2c61eb37ae ?
Limitations
Templates cannot be used to add non-static members or functions to classes. This limitation is either outdated or the compiler doesn't properly check this case. The given sample compiles without any warning/error.
|
I think this is a new feature because if you look at the assembly code the implicit 'this' reference/pointer is definitely intentionally being passed:
|
Links
- Corresponding page in the D Specification
- Template Examples
- Useful D Templates