Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template class specialization

I did read some of the related threads but still the issue was not clear:

#include <stdio.h>
#include <vector>
#include <iostream>

template <> class stack <int>
{
  public:
    std :: vector <int> stackVector;

};

The compilation error:

templateSpecializ.cpp:5: error: ‘stack’ is not a template
templateSpecializ.cpp:6: error: explicit specialization of non-template ‘stack’

From this link: coderSource.net

Have I missed some point? I feel I have. I even tried to define the functions there, but that was not helpful.

like image 719
Aquarius_Girl Avatar asked Apr 01 '11 08:04

Aquarius_Girl


2 Answers

That is a template specialisation of a template called stack. stack is not defined inany of those header files. If you wish to define a new template class you must first define the base case

template<typename T>
class stack
{
  //implementation goes here
};

template<>
class stack<int>
{
 public:
  std::vector<int> stackVector;
};

If you wish to only define stack for int and not for every type you can use

template<typename T> class stack;
template<>
class stack<int>
{
 public:
  std::vector<int> stackVector;
};
like image 121
Andrew Marsh Avatar answered Nov 11 '22 11:11

Andrew Marsh


You can not specialize your template if you don't have a template to specialize yet. So this should work:

template <typename T>
class stack
{
};

template <>
class stack<int>
{
  public:
    std::vector<int> stackVector;
};
like image 39
AVH Avatar answered Nov 11 '22 10:11

AVH