Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template not reporting error for local variable

Tags:

c++

templates

Why does this report an error:

class a {
public:
    void b() {this->c++;}
};

int main() {
    a var;
}

But this does not?

template <typename d> class a {
public:
    void b() {this->c++;}
}; 

int main() {
    a<int> var;
}

Despite the fact that "a" is a templated class, the function "b", or at least the access to the variable "c", does not depend on the type "d", so it should report something.

However, if I call "var.b();" in the main function it gives an error.

I know it is a simple question by I really can't figure it out.

like image 940
gmardau Avatar asked Sep 01 '26 01:09

gmardau


1 Answers

That's because the function a<int>::b() is not instantiated, due to the fact that it is a template. When you try to instantiate it, i.e. call it like var.b();, the compiler will spit an error. You have to understand that templates are instantiated "on demand", i.e. when the compiler needs the instantiation. Otherwise only minimal syntactic verifications take place. The details regarding instantiations/name lookups in templates is a rather complicated subject, I highly recommend this book: C++ Templates: The Complete Guide by David Vandevoode and Nicolai Josuttis.

That's not the case with the first code snippet: the function has to be valid from the very beginning.

like image 168
vsoftco Avatar answered Sep 03 '26 17:09

vsoftco