Home > front end >  Are there difference between fn(); and fn<T>(); in template class member function of C
Are there difference between fn(); and fn<T>(); in template class member function of C

Time:04-23

template <class T> class Stack {
public:
  Stack();
};
template <class T> class Stack {
public:
  Stack<T>();
}

By the way, what's the meaning of <T>?

CodePudding user response:

The difference is that the first piece of code is valid C , and the second one is not.

Some compilers accept the second piece of code since in older versions of C (pre C 11) that might have been one way to define constructors.

The <T> in Stack<T> would have been a way of referring to the current instantiation. The alternative way being the injected-class-name, where the bare name Stack inside the body of class Stack { will refer to itself with the appropriate template arguments filled in. The identifier in the constructor of a class must be this injected-class-name.

CodePudding user response:

From injected-class name in class template's documentation:

Otherwise, it is treated as a type-name, and is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.

This means that both the given snippets in your example are equivalent(Source). In the 1st snippet, the declaration Stack(); for the default ctor is actually the same as writing:

Stack<T>();  //this is the same as writing `Stack();`

what's the meaning of ?

Stack<T> denotes an instantiated class-type for some given T. For example, when T=int then Stack<int> is a separate instantiated class-type. Similarly, when say T=double then Stack<double> is another distinct instantiated class-type.

When instantiating a template(class or function) we generally(not always as sometimes it can be deduced) have to provide additional information like type information for template type parameters etc. And the way to provide this additional information is by giving/putting it in between the angle brackets.

For example,

template <class T> class Stack {
public:
  Stack();   //this is the same as Stack<T>(); due to injected class name in class template
};

template<typename T>
Stack<T>::Stack()
{
}
int main()
{
    Stack<int> obj;  //here we've provided the additional information "int" in between the angle brackets
    
}

The above code will generate a class type Stack<int> that will look something like:

template<>
class Stack<int>
{
  
  public: 
  Stack<int>() 
  {
  }
  
};
  •  Tags:  
  • c
  • Related