开发者

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
 开发者_Go百科       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


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).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜