非模板类中的函数模板 [英] 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)
{
}
但它不工作。我收到这个错误msg:
but it doesn't work. I'm getting this err msg:
'错误1错误C2768:'Stack_T :: put':非法使用显式模板参数
谢谢
'Error 1 error C2768: 'Stack_T::put' : illegal use of explicit template arguments'
Thank you
推荐答案
不要将< T>
函数名。这应该工作:
Don't put the <T>
after the function name. This should work:
template<class T>
void Stack_T::put(const T& obj)
{
}
$ b b
编辑:
如果函数定义不在头文件中,要解决这个问题,请使用以下方法之一:
This still won't work if the function definition is not in the header file. To solve this, use one of:
- 将函数定义放在类文件中的头文件中。
- 将函数定义放在类之后的头文件中(如在示例代码中)。
- 在头文件中使用显式模板instanciation。这有严重的限制(你必须提前知道所有可能的T值)。
这篇关于非模板类中的函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文