Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template in non-template class

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

like image 718
There is nothing we can do Avatar asked Nov 25 '09 19:11

There is nothing we can do


People also ask

Can a non template class have a template function?

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.

What is template function and template 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.

What is a 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.

What is difference between class template and function template in C++?

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.


1 Answers

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:

  • 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).
like image 86
interjay Avatar answered Oct 01 '22 01:10

interjay