Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this template parameters con­straint doesn't work?

Tags:

templates

d

Reading templates-revisited:

struct S(T : T*) {
  T t;  // t is supposed to be of type 'int*', but it's of type 'int', why?
}

void main() {

  int x = 123;
  S!(int*) s;
  static assert(is(typeof(s.t) == typeof(&x)));
}

The above code doesn't compile.

Strangely enough, the following does compile:

struct S(T : int*) {
  T t;
}

void main() {

  int x = 123;
  S!(int*) s;
  static assert(is(typeof(s.t) == typeof(&x)));
}

I don't understand this behavior. An explanation would be appreciated.

like image 728
Arlen Avatar asked Feb 21 '23 20:02

Arlen


1 Answers

When a type specialization (the type after the colon) is dependent on the parameter identifier, such as T : T*, the resulting identifier refers to the role of the identifier (T) in the type specialization (the deduced type) if there was a match.

Otherwise, if the specialization is independent, such as T : int*, the resulting identifier is an alias of the type specialization.

Examples:

=========================================================
Argument T        | Specialization     | Result
=========================================================
void              | T : void           | void
char              | T : void           | <no match>
int*              | T : T*             | int
immutable(char)[] | T : T[]            | immutable(char)
immutable(char)[] | T : immutable(T)[] | char
=========================================================

When there is a mismatch for an argument passed to a template parameter, the template is dropped from the overload set. An error is raised if the overload set becomes empty before a match is found.

When there is a mismatch in an IsExpression (the is(...) primary expression), the result is false and no symbols are introduced into scope.

like image 150
jA_cOp Avatar answered Mar 03 '23 21:03

jA_cOp