Template Specialization - member functions

359 views Asked by At

I'm having some problems with syntax(assumption) regarding declaration of member function in template specialization.

I have a simple class Stack that treats every type the same except strings

This is what I have so far

//stack.h

#ifndef STACK_H
#define STACK_H
#include <vector>
#include <deque>
#include <string>

template <typename T>
class Stack {

public:
    void push(T const&);
    void pop();

private:
    std::vector<T> _elems;
};

/* template specialization */
template <>
class Stack <std::string>{

public:
    void push(std::string const &s);
    void pop();

    private:
        std::deque<std::string> _elems;
};

#include "stack.tpp"
#endif // STACK_H

//stack.tpp

#include <stdexcept>

template <typename T>
void Stack<T>::push(T const& t)
{
    _elems.push_back(t);
}

template <typename T>
void Stack<T>::pop()
{
    if(!_elems.empty())
        _elems.pop_back();
}

template<>
void Stack<std::string>::push(std::string const& s)
{
    _elems.push_back(s);
}

template <>
void Stack<std::string>::pop()
{
    if(!_elems.empty())
        _elems.pop_back();
}

but i get error: template-id 'push<>' for 'void Stack<std::basic_string<char> >::push(const string&)' does not match any template declaration

I found some solutions that have member functions declared in .h file but I really want to avoid that.

So where have messed up? Feel free to also comment on the rest of the code(style, readability, efficiency)

1

There are 1 answers

0
dlf On BEST ANSWER

The template<> prefixes are not needed with the function definitions. This should be all you need:

void Stack<std::string>::push(std::string const& s)
{
    _elems.push_back(s);
}

void Stack<std::string>::pop()
{
    if(!_elems.empty())
        _elems.pop_back();
}