Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this compile when I make the class a template?

Tags:

c++

templates

I am purposely using the dot and arrow operator incorrectly, but I'm confused why it compiles when I decide to make the class a template.

Compiles:

template <class B> 
struct Boss {

  bool operator==( Boss & other ) {

    return this.x == other -> x;

  }

};

int main() {

}

Does not compile:

struct Boss {

  bool operator==( Boss & other ) {

    return this.x == other -> x;

  }

};

int main() {

}
like image 272
Kacy Avatar asked Sep 17 '25 20:09

Kacy


2 Answers

Templates are not fully checked for correctness if they are not instantiated. They are only checked for syntax. this.x, while not semantically correct (because this is not, and cannot be a type that supports that operation), is still syntactically correct.

like image 191
Benjamin Lindley Avatar answered Sep 20 '25 08:09

Benjamin Lindley


It compiles because templates are not checked until you use it. If you try to do something useful in your main(), it will give you a compile error.

like image 38
Polentino Avatar answered Sep 20 '25 09:09

Polentino