Why aren't unclaimed members of the template class created?

I was wondering when I create an instance of a class template specifying a template type parameter.
1) , why the non-called function is not installed ?.
2) Are they going to compile until I try to use it?
3) What is the logic of 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();

 }
+5
source share
4 answers

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

You do not always want this.

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

, , " , "? , .

, .

+3

- , . , , . , .

+6

: , " ", - , , , , , .

-, .

, , :

  template <typename E> 
  class myContainer {

      // Imagine that constructors, setup functions, etc. were here

      void sort();   // this function might make sense only if E has an operator< defined

      E max();   // compute the max element, again only makes sense with a operator<

      E getElement(int i);  // return the ith element

      E transmogrify();  // perhaps this operation only makes sense on vectors
  };

  // sort() and getElement() makes total sense on this, but not transmogrify()
  myContainer<int> mci;         

  // sort and max might not be needed, but getElement() and transmogrify() might
  myContainer<vector<double>> mcvd;        
+3

cat<int>::show() , . , . , , .

- , . . , , cat<int>, , show() - , . , , .

, " ", " "? . . ? , , ?

+2

All Articles