Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why uncalled template class members aren't instantiated?

I was wondering that when I create an instance of a class template with specifying the template type parameter.
1) why the non-called function do not get instatiated ? .
2) dont they get compiled until I try to use it ?
3) what is the logic behind this behavior ?

Example

template <class T>
class cat{
public:

T a;
void show(){
   cout << a[0];
}
void hello(){
   cout << "hello() get called \n";
}
}; 

int main(){
cat<int> ob1; // I know that show() did not get instatiated, otherwise I will get an    error since a is an int
ob1.hello();

 }
like image 786
AlexDan Avatar asked Jun 28 '12 20:06

AlexDan


2 Answers

Templates aren't code - they're a pattern used to make the actual code. The template isn't complete until you supply the parameters so the code can't be made ahead of time. If you don't call a function with a particular set of template parameters, the code never gets generated.

like image 169
Mark Ransom Avatar answered Oct 26 '22 23:10

Mark Ransom


If they instantiated the entire class, then you might get invalid code.

You don't always want that.

Why? Because in C++, it's difficult (and in some cases, outright impossible, as far as I know) to say, "only compile this code if X, Y, and Z are true".

For example, how would you say, "only my copy constructor if the embedded object can be copied"? As far as I know, you can't.

So they just made them not compile unless you actually call them.

like image 37
user541686 Avatar answered Oct 26 '22 23:10

user541686