views:

296

answers:

2

Hi, I'm sure that it is possible but I just can't do it, which is: How can I define function template inside non-template class? I tryied something like this:

class Stack_T
{
private:
void* _my_area;
static const int _num_of_objects = 10;
public:
/*
Allocates space for objects added to stack
*/
explicit Stack_T(size_t);
/*
Puts object onto stack
*/
template<class T>
void put(const T&);
/*
Gets last added object to the stack
*/
template<class T>
T& get()const;
/*
Removes last added object from the stack
*/
template<class T>
void remove(const T&);
virtual ~Stack_T(void);
};

template<class T> //SOMETHING WRONG WITH THIS DEFINITION
void Stack_T::put<T>(const T& obj)
{
}

but it doesn't work. I'm getting this err msg:

'Error 1 error C2768: 'Stack_T::put' : illegal use of explicit template arguments'
Thank you

A: 

Don't put the <T> after the function name. This should work:

template<class T>
void Stack_T::put(const T& obj)
{
}

Edit:

This still won't work if the function definition is not in the header file. To solve this, use one of:

  • Put the function definition in the header file, inside the class.
  • Put the function definition in the header file after the class (like in your example code).
  • Use explicit template instanciation in the header file. This has serious limitations though (you have to know all possible values of T in advance).
interjay
There is nothing we can do
A: 

Appologies to everyone who tryied help me with that question. What was my main mistake that I included in main .h file as with concrete class and I forgot that with templates the story is bit different and to do that one has to use inclusion or separation model, which I forgot about. Once again thank you and I'm sorry for bothering.

There is nothing we can do