Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Classes in C++

Tags:

c++

I was reading the topic Generic Classes .I got stuck at one point .Following is the piece of code

template <class StackType> class stack
{
    StackType stck[10];
    int tos;
public:
    stack() {tos=0;}
    void push(StackType ob);
    StackType pop();
};

My question is that in template <class StackType> class stack, there are two classes made (StackType and stack)?

I mean how does the compiler treat this as like making stack a nested class of StackType or something else?

like image 371
Freedom911 Avatar asked Dec 05 '22 09:12

Freedom911


2 Answers

It is not creating a second class, it is creating one class of type Stack where StackType is being supplanted by a user-given type. A better way to define this is to use typename (§14.1.2), which makes it more clear what is actually going on. For more information on templates, see C++ Templates.

What you are describing is nested classes in templates:

template <typename Type>
class Stack
{
public:
    class InnerType
    {
    };
};

In this example, InnerType is a class whose strong name is Stack<Type>::InnerType, which is a specific class based on the provided type. So if somewhere in code an object is created as follows:

auto x = new Stack<int>();

then a class of type Stack<int>::InnerType will exist. Template classes only exist in the assembly when they are used in code, so if no objects of any variation of Stack are implemented, the InnerType (of any template type) will not exist.

Also further detail about declaring templates is discussed here on SO.

like image 186
Will Custode Avatar answered Dec 09 '22 13:12

Will Custode


There is no second class. StackType is the template argument. You can think of it just as you think about the argument to a function with one argument. Unless called and provided its argument, the function cannot do anything. The same with the template class StackType, it is the type argument to the template type stack. When you provide a type[name] as argument to the template class you specialize the template class. All this argument providing and specialization happens at compilation time. For instance, the first time when the compiler meets something like

stack< int > stackVariable;

or

typedef stack< int > StackOfInts;

only then does it actually compiles and instatiates a type named stack< int > - a stack of integers. Until that moment there is no stack of anything.

After instantiation with int your class becomes:

template<>
class stack< int >
{
  int stck[10];
  int tos;
public:
  stack() {tos=0;}
  void push(int ob);
  int pop();
};
like image 30
CristiArg Avatar answered Dec 09 '22 15:12

CristiArg