2011-10-21 55 views
0

我在我的头文件中定义的模板如下: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â 

回答

4

正确的语法是:

template <typename T> 
BoundedBuffer<T>::BoundedBuffer(const unsigned int size) : 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; 
} 

注意可选参数不应该在函数的定义,但在ONY函数的声明中声明。

class aaa 
{ 
    // declaration 
    void xxx(int w = 10); 
}; 

// definition 
void aaa::xxx(int w) 
{ 
    ... 
} 

请注意,模板类的所有内容都应保留在H文件中。 “

”它们必须位于相同的翻译单元中,在某些库中将模板实现分离为一个.tpp(或其他扩展名)文件是相当普遍的,该文件随后包含在声明模板的.h中“。正如Michael Price所说。

模板不是正常类型,它们不能链接。 它们仅在请求时才被实例化。

请注意,构造函数字段初始值设定项需要“:”字符。

class MyClass 
{ 
public: 
    int x; 

    MyClass() : x(10) { /* note that i used : character */ } 
}; 
+0

谢谢:)它的工作原理。所以我应该将构造函数的实现移动到h文件中? 此外,使用BoundedBuffer 作为我的函数中的参数时,有什么不对: /*生产者*/ 监制::监制(BoundedBuffer 和缓冲,const int的农产品,const int的延迟) \t缓冲液(缓冲)产生(产生),结果产生(1),延迟(延迟){} “q1buffer.cc:42:错误:在缓冲区之前的预期初始化程序 – Garrett

+0

是所有必须由几个c文件使用的模板的实现应移动到标题文件。如果它只局限于一个C文件,那么当然你可以将所有内容保存在C文件中。 –

+0

关于你在这个评论中的第二个问题,我不明白! –

1

您必须在头中实现模板的所有方法,因为模板的用户需要能够看到这些方法为给定类型实例化它。

1

你的声明应该是:

template< typename T > 
BoundedBuffer<T>::BoundedBuffer(const unsigned int size) : size(size) {...} 

注意,它也必须在头文件,如@Dean波维提及。