template specialization problem

Feb 22, 2012 at 5:20pm
Hi Everyone,

I am facing compiler error with the following code in VS 2005; It points to template specialization declaration statement - class CStack <std::string>. Please let me know the mistakes in the code.


template <>
class CStack <std::string>
{

public:
void MyPush(const std::string& r_newElement);

private:
std::vector<std::string> m_vecElements;

};

void CStack<std::string>::MyPush (const std::string& element)
{
// ........
}

Feb 22, 2012 at 6:45pm
What's the error?
Feb 22, 2012 at 7:27pm
why use templates when it's always a string? try just this:
class CStack
{
public:
void MyPush(const std::string& r_newElement);

private:
std::vector<std::string> m_vecElements;

};

void CStack::MyPush (const std::string& element)
{
// ........
}
Feb 22, 2012 at 11:29pm
@webJose

error C2143: syntax error : missing ';' before '<' (points class CStack <std::string> declaration line).
error C2913: explicit specialization; 'CStack' is not a specialization of a class template (points class CStack <std::string> declaration line).


@viliml

Yes, you are right. The example I posted doesn't require any template specialization; however, I like to know how we can use template specialization in simple class?
Feb 22, 2012 at 11:40pm
error C2913: explicit specialization; 'CStack' is not a specialization of a class template (points class CStack <std::string> declaration line).


You cannot specialize a non-template class.

What this means is you haven't defined a class template for CStack yet. In other words, you cant specialize something that doesn't exist "generically".

First you need to write your template class:
1
2
3
4
5
6
7
8
9
template<class T>
class CStack
{
   //.. constructors
   //.. member functions
   //.. data...
  private:
    std::vector<T> m_vecElements;
}


Then and only then can you specialize..
1
2
3
4
5
6
7
8
9
template<>
class CStack<std::string>
{
   //.. constructors
   //.. member functions
   //.. data...
  private:
    std::vector<std::string> m_vecElements;
}
Last edited on Feb 22, 2012 at 11:41pm
Feb 23, 2012 at 12:18am
Thanks clanmjc. It does work perfectly, and I understand too.
Topic archived. No new replies allowed.