C++:初始化头文件中声明的模板构造函数/例程?
我在头文件中定义了一个模板,如下所示:
template<typename T> class BoundedBuffer {
unsigned int size;
T entries[];
public:
BoundedBuffer( const unsigned int size = 10 );
void insert( T elem );
T remove();
};
但是,当我尝试初始化构造函数时:
BoundedBuffer<T>::BoundedBuffer( const unsigned int size = 10 ) size(size) {
// create array of entries
entries = new T[size];
// initialize all entries to null
for(int i = 0; i < size; i++)
entries[i] = null;
}
出现以下错误(上一个代码块的第一行是 17):
q1buffer.cc:17: error: âTâ was not declared in this scope
q1buffer.cc:17: error: template argument 1 is invalid
q1buffer.cc:17: error: expected initializer before âsizeâ
I have a template defined in my header file as follows:
template<typename T> class BoundedBuffer {
unsigned int size;
T entries[];
public:
BoundedBuffer( const unsigned int size = 10 );
void insert( T elem );
T remove();
};
However, when I try to initialize the constructor:
BoundedBuffer<T>::BoundedBuffer( const unsigned int size = 10 ) size(size) {
// create array of entries
entries = new T[size];
// initialize all entries to null
for(int i = 0; i < size; i++)
entries[i] = null;
}
I get the following error (the first line of the previous code block is 17):
q1buffer.cc:17: error: âTâ was not declared in this scope
q1buffer.cc:17: error: template argument 1 is invalid
q1buffer.cc:17: error: expected initializer before âsizeâ
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正确的语法是:
请注意,可选参数不应在函数定义中声明,而只能在函数声明中声明。
请注意,模板类的所有内容都应保留在 H 文件中。
“它们必须位于同一个翻译单元中。在某些库中,将模板实现分离到 .tpp(或其他扩展名)文件中,然后将其包含在声明模板的 .h 中是很常见的。”正如迈克尔·普莱斯所说。
模板不是普通类型,无法链接。
它们仅在请求时才被实例化。
请注意,构造函数字段初始值设定项需要“:”字符。
The right syntax is:
Note that optional parameters should not be declared in functions definitions but ony in functions declarations.
Note that everything for templated class should stay in H files.
"They must be in the same translation unit. It is quite common in some libraries to separate the template implementation into a .tpp (or some other extension) file that is then included in the .h where the template is declared." as Michael Price said.
Templates are not normal types and they cannot be linked.
They are instantiated only when requested.
Note that constructors fields initializers need the ":" character.
您必须在标头中实现模板的所有方法,因为模板的用户需要能够看到这些方法来为给定类型实例化它。
You have to implement all methods of the template in the header, because users of the template need to be able see those methods to instantiate it for a given type.
您的声明应该是:
请注意,它也必须位于头文件中,正如@Dean Povey 提到的那样。
Your declaration should be:
Note that it also has to be in the header file, as mentioned by @Dean Povey.