Template Question
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Sun Nov 19 19:42:02 UTC 2017
On Sunday, November 19, 2017 19:25:40 Jiyan via Digitalmars-d-learn wrote:
> With working i mean that
> Text X;
> Doesnt compile!
Okay. For starters,
struct Text(T : char)
{
size_t _len;
T* _ptr;
}
is a template specialization, which means that it's only going to compile if
T is char or a type that implicitly converts to char. It's similar (but not
quite the same as) doing
struct Text(T)
if(is(T : char))
{
}
https://dlang.org/spec/template.html#TemplateTypeParameterSpecialization
I suspect that what you meant to do was
struct Text(T = char)
{
size_t _len;
T* _ptr;
}
which would make char the default value for T. However, not even that is
going to allow you to do
Text t;
There is no implicit instantiation of templated types. Having the default
value for T will allow you to do
Text!() x;
instead of
Text!char x;
but it won't allow you to do
Text x;
and there's no way to do that. Templated types must always be explicitly
instantiated. What you could do that would give you a similar effect would
be to do
struct TextImpl(T)
{
size_t len;
T* ptr;
}
alias Text = TextImpl!char;
and then when you use Text, it will be replaced with TextImpl!char, which
would allow you to do
Text x;
The only time that templates are ever implicitly instantiated is with
function templates where all of the template parameters can be inferred from
the function arguments. It never occurs with any other kind of template,
even if the template has no parameters.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list