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);
virtual ~Stack_T(void);
// 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&);
};
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 non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.
A template allows us to create a family of classes or family of functions to handle different data types. Template classes and functions eliminate the code duplication of different data types and thus makes the development easier and faster. Multiple parameters can be used in both class and function template.
Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
Don't put the <T>
after the function name. This should work:
template<class T>
void Stack_T::put(const T& obj)
{
}
This still won't work if the function definition is not in the header file. To solve this, use one of:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With